Python- 检查用户是否输入了列表中的某些词

2024-04-19 21:28:50 发布

您现在位置: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(user in words1 for words1 in user):  #This part is probably the problem
    print("answer")

如果用户在另一个文件中键入列表中列出的任何单词,则程序应显示answer。如果用户没有键入列表中的任何单词,则不打印任何内容

抱歉,我不够精确,我的意思是,我想让用户写一个句子,像“电话屏幕坏了”,然后我想让程序看看单词列表称为words1和words2,然后找到单词“屏幕”内的words1文件

image


Tags: 文件用户txt列表readopen单词file1
2条回答

count(element)

function returns the occurrence count of given element in the list. If its greater than 0, it means given element exists in list.

示例:

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

或者

if user in words1 + words2:    # search the string in the concatenated list
    print("answer")

编辑:

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

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

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

为此,您必须下载nltk包

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")

相关问题 更多 >