简体   繁体   English

Python-检查用户是否输入了列表中的单词之一

[英]Python- Check if user typed one of those words that are in the list

How do i check if the user wrote a word that matches any of the words in a list i made in another file?我如何检查用户写的单词是否与我在另一个文件中创建的列表中的任何单词相匹配?

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

if the user types any of the words that are listed in a list in another file then the program should display answer.如果用户键入在另一个文件的列表中列出的任何单词,则程序应显示答案。 if the user does not type any of the words that are in the list then don't print anything如果用户没有输入列表中的任何单词,则不要打印任何内容

sorry i was not precise enough, what i meant is that i want the user to write a sentense like "the phone screen is broken" and then i want the program to look in the lists of words called words1 and words2 and then to find the word "screen" inside of the words1 file.抱歉,我不够精确,我的意思是我希望用户写一个句子,例如“手机屏幕坏了”,然后我希望程序查看名为 words1 和 words2 的单词列表,然后找到word1 文件中的“屏幕”一词。

image图片

count(element) : 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.如果它大于 0,则表示给定元素存在于列表中。

example:例子:

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

OR或者

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

EDIT:编辑:

The concatenated solution could cause memory issues, we could also opt for chain using itertools:串联解决方案可能会导致内存问题,我们也可以选择使用 itertools 的chain

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

After converting both files into strings words1, words2 just follow these steps:将两个文件都转换为字符串 words1、word2 后,只需执行以下步骤:

For this you must download nltk package为此,您必须下载 nltk 包

pip install nltk

Then然后

from nltk.tokenize import word_tokenize

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM