2017-11-23 1 views
0

テキストファイル内の単語のセットを一致させる必要があります。 単語のセットは、別々の行に別々に表示されます。 発生回数は関係ありませんが、少なくとも1回発生する必要があります。 すべての単語が正確に一致する場合のみ、それはPASSです。そうでない場合、テストはFAILです。Python - 既存のテキストファイルに存在する文字列のリストと一致させる

私は内容でファイルを作成しました:コードは単一の文字列のために動作しますが、リストでは動作しません下

file1 = open("MyFile.txt","a+") 

は今、リストは

list = ["SIMPLE", "QUICK", "ADVANCED"] 

です。

with open("C:/Users/vikp/Desktop/MyFile.txt") as file1: 
     for line in file1: 
      if list in line: 
       <assert pass condition> 
      else: 
       <assert fail condition> 
+0

サンプルと比較する前に '.strip()'を呼び出す必要があります。 –

+0

ファイルに「シンプル」、「クイック」、「アドバンス」以外の言葉を許可しますか? –

+1

'MyFile.txt'の内容はどうなっていますか? –

答えて

1

各行には1単語しかありません。その場合は、line in mylistで行の有効性をテストすることができます。このコードでは、mylist以外の単語は許可しないものとしています。

occurred = set() # this set tests for at least one occurrence of each word 
with open("C:/Users/vikp/Desktop/MyFile.txt") as file1: 
    for word in file1: 
     word = word.strip() # get rid of new-line or whitespace characters 
     if word in mylist: # assume one word per line 
      occurred.add(word) 
     else: 
      raise ValueError(word + ' is not in mylist') 
# success if the for loop finishes without error AND all words occurred at least once 
if len(occurred) == len(mylist): 
    print('success') 
else: 
    missing = set(mylist) - occurred 
    raise ValueError('the following words are missing: '+str(missing)) 
+0

"少なくとも1つのオカレンス"のアカウントに私の答えを更新しました。 –

0

使用がリストの代わりに設定し、正規表現でこのソリューションを試すことができます。

SIMPLE and QUICK are winners they are ADVANCED too. 
SIMPLE and QUICK are winners they are ADVANCED too. 
SIMPLE and QUICK are winners they are ADVANCED too wowow. 

が出力:

import re 
list = {"SIMPLE", "QUICK", "ADVANCED"} 

with open('file.txt','r') as f: 
    for line in f: 
     match=set() 
     for item in list: 
      if re.findall(item,line): 
       match.add("".join(re.findall(item,line))) 


     if list-match==set(): 
      print(" Test pass") 
      #<assert pass condition> 
     else: 
      print("Test fail") 
      #<assert fail condition> 

私は含まれていfile.txtを持つテストを持っています

Test pass 
Test pass 
Test pass 

私はダミーファイルで試したように、正規表現は完全に一致しません。

関連する問題