通过for循环检查字典中是否存在单词

尝试使用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。

pqlay 回答:通过for循环检查字典中是否存在单词

首先,您不必写str(word) in wordlist == Truestr(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())

祝您工作顺利!

,

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 :

尽管后者毫无意义。

,

根据您想要的结果,我将字典中的键检查更改为

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
本文链接:https://www.f2er.com/3128646.html

大家都在问