尝试使用for loop
内的.txt文件创建具有字数统计的字典
def countWords(filename):
wordlist = {}
infile = open(filename)
for line in infile:
for word in line.split():
if str(word) in wordlist == True :
wordlist[word] += 1
print("old found word")
else:
wordlist[word] = 1
print(" NOT found old word")
return wordlist
我希望此函数创建输出单词列表,并列出单词及其在整个文本文件中的计数。而是循环不断地打印“找不到旧单词”,并输出单词列表字典将列出所有单词,但它们的计数都为1。
答案 0 :(得分:2)
首先,您不必写str(word) in wordlist == True
,str(word) in wordlist
就足够了。
其次,无需将单词从文件转换为str
类。
第三,优良作法是在打开文件时使用with
运算符,以防止某些内存泄漏,因此应该是
with open(filename) as infile:
#your_code
第四,如果print
行不是必需的,那么pythonic
的写法将更多:
from collections import Counter
text = """Lorem ipsum dolor sit amet, consectetuer adipiscing elit,
sed diam nonummy nibh euismod tincidunt ut laoreet dolore
magna aliquam erat volutpat"""
wordline = dict(Counter(text.split())
祝您工作顺利!
答案 1 :(得分:1)
行
if str(word) in wordlist == True :
评估如下:
首先,评估断言wordlist == True
并返回False
。
这导致了表达
if str(word) in False :
也是False
。
因此,将触发else:
语句。
要解决此问题,您可以忽略== True
:
if str(word) in wordlist:
或使用括号:
if (str(word) in wordlist) == True :
尽管后者毫无意义。
答案 2 :(得分:0)
根据您想要的结果,我将字典中的键检查更改为
if str(word) in wordlist:
为您提供以下功能。
def countWords(filename):
wordlist = {}
infile = open(filename)
for line in infile:
for word in line.split():
if str(word) in wordlist:
wordlist[word] += 1
print("old found word")
else:
wordlist[word] = 1
print(" NOT found old word")
return wordlist