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



所以我正在编写一个程序,它将接受用户输入,然后将用户输入与集合列表进行比较,然后告诉我给定列表中有多少来自用户输入的单词。

例如:

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.

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

谢谢。

len([word for word in user_in if word in list])

尝试如下:

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

好吧,您可以使用user_in.split(' '(拆分用户输入。 然后将user_in_list中的每个单词与检查列表中的单词进行比较,并在这种情况下增加计数器:

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)

试试这个,

l1 = ['I','like','apples']    # set list
user = input('Say a phrase:')
a=user.split(' ')
k=0
print(a)
for i in l1:
if i in l1:
k+=1
print("similar words:",k)

希望对您有所帮助!

通过使用函数 split((,您可以将给定的短语拆分为单词。 最好使用 ui.lower(( 或 ui.upper(( 来避免区分大小写

li = ['i', 'like', 'apples']    #initial list
ui = input('say a phrase')      #taking input from user
ui = ui.lower()                 #converting string into lowercase
ui_list = ui.split()            #converting phrase into list containing words
count = 0
for word in ui_list:
if word in li:
print(word)
count += 1
print(count)                     #printing matched words

相关内容

最新更新