免責事項: Python の学習を始めたばかりです。
単語がテキストファイルに出現する回数をカウントし、その単語をキー、カウントを値として設定し、辞書「book_index」に格納する関数があります。これが私のコードです:
alice = open('location of the file', 'r', encoding = "cp1252")
def book_index(alice):
"""Alice is a file reference"""
"""Alice is opened, nothing else is done"""
worddict = {}
line = 0
for ln in alice:
words = ln.split()
for wd in words:
if wd not in worddict:
worddict[wd] = 1 #if wd is not in worddict, increase the count for that word to 1
else:
worddict[wd] = worddict[wd] + 1 #if wd IS in worddict, increase the count for that word BY 1
line = line + 1
return(worddict)
その辞書を「裏返し」にして、カウントをキーとして使用し、x 回出現する単語を値として使用する必要があります。例: [2, 'hello', 'hi'] テキスト ファイルに 'hello' と 'hi' が 2 回表示されます。
既存の辞書をループする必要がありますか、それともテキスト ファイルを再度ループする必要がありますか?