首页 > 解决方案 > 定义一个单词列表并检查这些单词中的任何一个是否存在于文本正文中

问题描述

你能帮我解决以下问题的逻辑吗?我想定义一个不同单词的列表并检查这些单词是否存在于文本中,如果存在,我想要返回单词,如果这些单词不是文本的一部分,我想要返回一条消息。

我的代码如下:

def search_word():
with open('testing.txt', 'r') as textFile:
    word_list = ['account', 'earn', 'free', 'links', 'click', 'cash', 'extra', 'win', 'bonus', 'card']
    for line in textFile.read():
        for word in word_list:
            if word in line:
                print(word)
            else:
                print('The text does not include any predefined words.')

search_word()

我得到的输出是 else 语句。我知道问题出在“for line in textFile.read()”代码上,但是我试图理解为什么逻辑在上面的代码中不起作用。

通过在 for 循环命令之前移动“fileText = textObjet.read()”来更改以下代码,我得到了正确的结果。

def search_word():
with open('email.txt', 'r') as textObject:
    fileText = textObject.read()
    word_list = ['account', 'earn', 'free', 'links', 'click', 'cash', 'Extra', 'win', 'bonus', 'card']
    for word in word_list:
        if word in fileText:
            print(word)
        else:
            print(word, '- the email does not include any predefined spam words.')

搜索字()

感谢您在理解逻辑差异方面的帮助。

谢谢。

露易丝

标签: python-3.x

解决方案


假设 testing.txt 仅包含一个单词accountread()将您的文本文件作为字符串返回,例如'account\n'.

for line in textFile.read():正在读取该字符串中的每个字符(包括空格和换行符),例如['a', 'c', 'c', 'o', 'u', 'n', 't', '\n'],然后 for word in word_list:将 word_list 中的单词与每个字符进行比较。10 个单词到 'a',然后 10 个单词到 'c' ...最后 10 个单词到 \n。没有一个单词比较是匹配的,所以我们将执行 80 个(10 个单词 x 8 个字符)else 语句。

fileText = textObject.read()不使用 for 循环的情况下,for word in word_list:只需将 word_list 中的单词与该字符串进行比较。'account' 到 'account\n','earn' 到 'account\n' ... 'card' 到 'account\n'。这次只为您拥有的 10 个单词返回 10 个结果。


推荐阅读