2017-03-29 4 views
1

私は2つのテキストファイルを比較する能力が必要です。ファイル1はチャットログであり、ファイル2はキーワード付きの単語リストです。ファイル2のキーワードの1つがファイル1であるチャットログに表示されるたびに理想的に表示されている出力を得るのに苦労しています。どのように私はこの出力を達成することができるかについての任意のアイデア?Pythonでテキストファイルを別のテキストファイルと比較するには?

編集*

これは私が現在使用しようとしているコードである、しかし、私が得る出力は、それがGUI内のテキストボックスに両方のファイルを印刷していることです。出力の必要性は、ファイル2内の単語がファイル1内でどの行に現れるかを示すことです。コードの一部は、すでに働いているキーワード検索機能から取得されたものです。

def wordlistsearch(): 

filename = tkFileDialog.askopenfile(filetypes=(("Text files", "*.txt") ,)) //file1 
mtxt = filename.readline() 
i =0 
filename2 = tkFileDialog.askopenfile(filetypes=(("Text files", "*.txt") ,)) //file2 

while i<10000: 
    keystring = filename2.readline() 
    print keystring 
    participant = mtxt.split("(")[0] 
    temppart2 = mtxt.split("(")[-1] 
    keyword = temppart2.split(")")[0] 
    if mtxt.find(str(keystring)) != -1: 
     print i, ": ", mtxt 
    i=i+1 
    mtxt = filename.readline() 
+1

何を試しましたか?あなたのコードの例と、それがうまくいかない理由の詳細を含めてください。 – asongtoruin

+0

もっと具体的に、両方のファイルの例を投稿して、これまで何をやっていますか? –

答えて

1

あなたはFile2の中にもあるファイル1内のすべての単語を検索したい場合は、あなたが使用することができます。

keywords = set([word for line in open("keyword_file","r") for word in line.split()]) 

words = set([word for line in open("log_file","r") for word in line.split()]) 

common = words.intersection(keywords) 

を代わりにファイル1を読みながら試合の発生を確認するには:

keywords = set([word for line in open("keyword_file","r") for word in line.split()]) 

for line in open("log_file","r"): 
    for word in line: 
     if word in keywords: 
      print "found {0} in line {1}".format(word, line) 
+1

これは非常に良いアプローチです。 –

0

これは非常に良い質問です。個人的に私はあなたがこれを行うことができると思います。最後keywords_dict

# I suppose the keywords has non repeated words separated by a space 
keywords_file = open('path_to_file_keywords') 
keywords_dict = {word: 0 for word in keywords_file.readlines().strip().split(' ')} # Iterate through all the words removing '\n'characters and generate a dict 

# Then read the chat log 
chat_log_file = open('path_to_file_chat_log') 
chat_log_words_generator = (word for word in chat_log_file.readlines().strip().split(' ')) # Create a generator with the words from the chat log 


for word in chat_log_words_generator: 
    try: 
     word_count = keywords_dict[word] 
    except KeyError: 
     continue # The word is not a keyword 
    word_count += 1 # increment the total 
    keywords_dict[word] = word_count # override the value of the count in the dict 

は、すべてのキーワードの出現回数を持つべきです。

+1

の代わりに、キーワードの合計発生数が増えています。これを変更して、チャットログ内でキーワードがどの行に表示されるかを表示しますか?特定の単語が出現するすべての行を印刷するキーワード検索機能が既に用意されています。乾杯! –

+0

大きな質問! 'readlines'で' enumerate'を使うと、 '(index、item)'のようなタプルが得られます: '' index(index、line.strip()in enumerate(chat_log_file.readlines()) ' 。この発電機を使用すると、以前のように言葉を得ることができます。 –

+0

私はtkinterを使用しているので、open( 'path_to_file_chat_log')行をtkFileDialog.askopenfile(filetypes =( "テキストファイル"、 "* .txt")))のように変更することができます。ボタンをクリックした後に比較するファイルを選択することができます。 –

関連する問題