从单词列表中比较用户输入

2024-04-24 04:42:28 发布

您现在位置:Python中文网/ 问答频道 /正文

因此,我正在编写一个程序,它将接收用户输入,然后将用户输入与一个设置列表进行比较,然后告诉我给定列表中有多少来自用户输入的单词

例如:

list = ['I','like','apples']    # set list

user_in = input('Say a phrase:')

# the user types: I eat apples.
#
# then the code will count and total the similar words 
#  in the list from the user input.

我已经接近这一点,我知道我可能必须将用户输入转换为列表本身。只是需要帮助比较和计算匹配的单词

多谢各位


Tags: the用户in程序列表input单词list
3条回答
len([word for word in user_in if word in list])

那么,您可以使用user_in.split(“”)分割用户输入。 然后将user_in_列表中的每个单词与检查列表中的一个单词进行比较,在这种情况下增加计数器:

list = ['I','like','apples'] # set list

user_in = input('Say a phrase:')

ui = user_in.split(' ')

count = 0
for word in ui:
    if word in list:
        count += 1

print(count)

试着这样做:

similarWords=0 #initialize a counter for word in user_in.split(): if word in list: #check and compare if word is in set list similarWords+=1 #increase counter by 1 every time a word matches

相关问题 更多 >