免责声明:我刚刚开始学习 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' 在文本文件中出现两次。
我是否需要循环浏览我现有的字典或再次循环浏览文本文件?