Python-检查用户是否键入了列表中的其中一个单词

Python-检查用户是否键入了列表中的其中一个单词,python,Python,如何检查用户编写的单词是否与我在另一个文件中创建的列表中的任何单词匹配 file1 = open('Screen.txt', 'r') file2 = open('Battery.txt', 'r') words1 = str(file1.read().split()) words2 = str(file2.read().split()) print(words1) user = str.lower(input("type what is your problem?")) if any(use

如何检查用户编写的单词是否与我在另一个文件中创建的列表中的任何单词匹配

file1 = open('Screen.txt', 'r')
file2 = open('Battery.txt', 'r')
words1 = str(file1.read().split())
words2 = str(file2.read().split())
print(words1)

user = str.lower(input("type what is your problem?"))
if any(user in words1 for words1 in user):  #This part is probably the problem
    print("answer")
如果用户键入另一个文件列表中列出的任何单词,则程序应显示答案。如果用户没有键入列表中的任何单词,则不要打印任何内容

对不起,我不够精确,我的意思是,我想让用户写一个句子,比如“电话屏幕坏了”,然后我想让程序在单词列表中查找单词1和单词2,然后在单词1文件中找到单词“screen”

计数(元素):

函数返回列表中给定元素的出现次数。如果 大于0,表示列表中存在给定元素

例如:

user = 'c'
words1 = ['a','b']
words2 = ['c', 'd']
if words1.count(user) > 0 or words2.count(user) > 0:
    print("answer")

编辑:

连接的解决方案可能会导致内存问题,我们也可以使用itertools选择
chain

from itertools import chain
if user in chain(words1, words2):
    print("answer")

将两个文件转换为字符串words1后,words2只需执行以下步骤:

为此,您必须下载nltk包

pip install nltk
然后


如果
any()中的words1.count(user)>0或words2.count(user)>0
循环是无序的。你能具体说明你需要检查哪一张表吗?@dawid 777你能解决这个问题吗?如果是,您可以点击勾号接受答案,干杯
pip install nltk
from nltk.tokenize import word_tokenize

w1=set(word_tokenize(words1))
w2=set(word_tokenize(words2))

if input() in w1.union(w2):
   print("something")