python-3.x - 定义一个单词列表并检查这些单词中的任何一个是否存在于文本正文中
问题描述
你能帮我解决以下问题的逻辑吗?我想定义一个不同单词的列表并检查这些单词是否存在于文本中,如果存在,我想要返回单词,如果这些单词不是文本的一部分,我想要返回一条消息。
我的代码如下:
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.')
搜索字()
感谢您在理解逻辑差异方面的帮助。
谢谢。
露易丝
解决方案
假设 testing.txt 仅包含一个单词account
,read()
将您的文本文件作为字符串返回,例如'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 个结果。
推荐阅读
- c++ - (1)为什么它不能识别这是一个回文&(2)我如何让它打印带有空格的原始输入?
- c++ - 从“const QString”到“QTreeWidgetItem”的函数式转换没有匹配的转换
- jquery - 如何延迟淡出的功能?
- plot - 单独的 EPSlatex 不添加 \end{document}
- java - 如何编写一个在某些列值中生成数字的数组生成器?
- java - 将基类参数传递给具有子类签名的方法
- vba - 尝试调用函数时出现名称错误
- wordpress - WPBakery 页面构建器拉伸图像全宽
- java - 忽略在正则表达式中创建单词的开头
- accessibility - Cypress 和 Axe 似乎忽略了内容安全策略