0

他のテキスト ドキュメントで検索する必要がある単語を含む語彙ファイルがあります。見つかった場合、各単語の数を見つける必要があります。例えば:

語彙.txt:

thought
await
thorough
away
red

test.txt:

I thought that if i await thorough enough, my thought would take me away.
Away I thought the thought.

最終的に、思考のインスタンスが 4 つあることを確認する必要があります。私はこの方法で試しました:

for vocabLine in vocabOutFile:
    wordCounter = 0
    print >> sys.stderr, "Vocab word:", vocabLine
    for line in testFile:
        print >> sys.stderr, "Line 1 :", line
        if vocabLine.rstrip('\r\n') in line.rstrip('\r\n'):
            print >> sys.stderr, "Vocab word is in line"
            wordCounter = wordCounter + line.count(vocabLine)
            print >> sys.stderr, "Word counter", wordCounter
    testFile.seek(0, 0)

デバッグ中に、一致した文字列の末尾にある単語を適切にカウントしていると判断したため、vocab ファイルの戻り文字のためにファイル内の単語を認識していないという奇妙な感覚があります。ただし、rstrip() を使用した後でも、カウントは正しくカウントされません。これがすべて完了したら、語彙リストから 2 回以上出現しない単語を削除する必要があります。

私は間違って何をしていますか?

ありがとう!

4

2 に答える 2

2

語彙の辞書を作成することをお勧めします。

vocab_counter = {vocabLine.strip().lower(): 0 for vocabLine in vocabOutFile}

次に、testFile を 1 回だけスキャンして (より効率的です)、単語ごとにカウントを増やします。

for line in testFile:
    for word in re.findall(r'\w+', line.lower()):
        if word in vocab_counter:
            vocab_counter[word] += 1
于 2013-05-29T21:54:04.983 に答える
2

regexと_collections.Counter

import re
from collections import Counter
from itertools import chain

with open("voc") as v, open("test") as test:
    #create a set of words from vocabulary file
    words = set(line.strip().lower() for line in v) 

    #find words in test file using regex
    words_test = [ re.findall(r'\w+', line) for line in test ]

    #Create counter of words that are found in words set from vocab file
    counter = Counter(word.lower()  for word in chain(*words_test)\
                                          if word.lower() in words)
    for word in words:
        print word, counter[word]

出力

thought 4
away 2
await 1
red 0
thorough 1
于 2013-05-29T21:51:33.723 に答える