2
我正在將文本文件作爲輸入並創建一個函數來計算哪個單詞最頻繁出現。如果兩個或更多的單詞出現頻率最高且相等,我將打印所有這些單詞。TypeError:不可用類型:'list' - 創建頻率函數
def wordOccurance(userFile):
userFile.seek(0)
line = userFile.readline()
lines = []
while line != "":
if line != "\n":
line = line.lower() # making lower case
line = line.rstrip("\n") # cleaning
line = line.rstrip("?") #cleans the whole docoument by removing "?"
line = line.rstrip("!") #cleans the whole docoument by removing "!"
line = line.rstrip(".") #cleans the whole docoument by removing "."
line = line.split(" ") #splits the texts into space
lines.append(line)
line = userFile.readline() # keep reading lines from document.
words = lines
wordDict = {} #creates the clean word Dic, from above
for word in words: #
if word in wordDict.keys():
wordDict[word] = wordDict[word] + 1
else:
wordDict[word] = 1
largest_value = max(wordDict.values())
for k in wordDict.keys():
if wordDict[k] == largest_value:
print(k)
return wordDict
請幫助我使用此功能。
哪一行產生錯誤?在某些時候(可能是'wordDict [word] = 1'),您正嘗試使用列表作爲字典鍵,這是不允許的。 – elethan
這一行給我的錯誤消息:如果在wordDict.keys()中的單詞: –
我想不出任何方式可以從該行中得到該錯誤。我發佈的解決方案適合您嗎?如果不是的話,你能否在你的問題中發佈你錯誤的完整回溯,以便我能更好地幫助你? – elethan