1

入力として 2 つのファイルを受け取るコードがあります: (1) 辞書/レキシコン (2) テキスト ファイル (1 行に 1 文)

私のコードの最初の部分は、辞書をタプルで読み取るため、次のような出力が得られます。

('mthy3lkw', 'weakBelief', 'U')

('mthy3lkm', 'firmBelief', 'B')

('mthy3lh', 'notBelief', 'A')

コードの 2 番目の部分は、テキスト ファイル内の各文を検索して、これらのタプルの位置 0 にある単語を検索し、文、検索単語、およびそのタイプを出力します。

したがって、文 mthy3lkw ana mesh 3arif が与えられた場合、望ましい出力は次のとおりです。

["mthy3lkw ana mesh 3arif", ' mthy3lkw ', 'weakBelief', 'U'] 強調表示された単語が辞書にある場合。

コードの 2 番目の部分 (マッチング部分) が遅すぎます。どうすれば速くなりますか?

これが私のコードです

findings = [] 
for sentence in data:  # I open the sentences file with .readlines()
    for word in tuples:  # similar to the ones mentioned above
        p1 = re.compile('\\b%s\\b'%word[0])  # get the first word in every tuple
        if p1.findall(sentence) and word[1] == "firmBelief":
            findings.append([sentence, word[0], "firmBelief"])

print findings  
4

2 に答える 2

1

タプルから正しいものをすばやく見つけることができるように、dictルックアップ構造を構築します。次に、ループを再構築して、各文の辞書全体を調べてすべてのエントリを一致させようとする代わりに、文の各単語を調べて辞書の辞書で検索するようにします。

# Create a lookup structure for words
word_dictionary = dict((entry[0], entry) for entry in tuples)

findings = []
word_re = re.compile(r'\b\S+\b') # only need to create the regexp once
for sentence in data:
    for word in word_re.findall(sentence): # Check every word in the sentence
        if word in word_dictionary: # A match was found
            entry = word_dictionary[word]
            findings.append([sentence, word, entry[1], entry[2]])
于 2012-10-08T22:32:11.573 に答える
1

タプルのリストをtrieに変換し、それを検索に使用します。

于 2012-10-07T03:20:19.070 に答える