私は巨大なテキストファイルをファイル内の各単語の行番号を含む辞書に索引付けしています。次のコードは、私が持っているものです。Pythonディクショナリは常にどのキーでも同じ値を返します
i = {} # The dictionary
with open("infl2.txt", "r") as f:
for index, line in enumerate(f): # step through each line
line = line.lower() # for case insensitive key matching later on
if index == 21: # Print part of the dictionary for debug
print i
for w in line.split(): # Split line into words and iterate
i[w] = index # Add word to dictionary with line number as value
# TESTING
s = 'aa'
index = i[s]
print s + " -> " + str(index)
print len(i)
出力:
{'aa': 1, 'adhs': 12, 'ac': 9, 'ab': 4, 'ad': 11, 'afaik': 17, 'ai': 19, 'afps': 18, 'adrs': 15, 'as': 0, 'abcs': 5, 'aases': 3, 'aids': 20, 'abc': 5, 'abd': 6, 'ads': 11, 'adp': 13, 'aarp': 2, 'abm': 8, 'acth': 10, 'abs': 4, 'abls': 7, 'afp': 18, 'adh': 12, 'abds': 6, 'aec': 16, 'aidses': 20, 'adps': 14, 'adr': 15, 'a': 0, 'aecs': 16, 'adpses': 14, 'acths': 10, 'ais': 19, 'acs': 9, 'ablses': 7, 'aarps': 2, 'afaiks': 17, 'aas': 3, 'abms': 8}
aa -> 112505
252362
あなたはの1行目にダンプO」20で見られた値1
を(返す必要があり、「AA」を見ることができるように出力)。ただし、112505
が返されます。これはfile length (in lines) - 1
です。どんなキーでテストしても、常に112505
を返します。
なぜこのようなことが起こるのかわからないので、私は救いの手に感謝します。
あなたは 'i [w] = index'を実行し、indexは現在の行番号です。もちろん、辞書内のすべての単語は、すべての行のすべての単語についてそれを行った後、最後の行番号に設定されます。 – RemcoGerlich
辞書の各値は、その単語が出現する最後の行になります。 – RemcoGerlich
@RemcoGerlichすべての単語が最後の行にある場合はyesです。 –