首页 > 解决方案 > 获取用户输入的句子/字符串并比较列表中的项目,如果句子中的关键字与列表项匹配,则返回列表条目

问题描述

我有一个清单

List1 = ['Cappuccino','Café Latte','Expresso','Macchiato ','Irish coffee ']

我必须从用户那里获取输入句子,如果 List1 中的任何单词匹配应该返回该 list1 中的字符串以及一些图例。

示例:输入您的输入字符串:用户输入:I want 1 Cappuccino. 预期输出:item : Cappuccino

我的代码:

import pandas  as pd
import re
def ccd():
    List1 = ['Cappuccino','Café Latte','Expresso','Macchiato ','Irish coffee '],
             
    for i in range(len(List1)):
        List1[i] = List1[i].upper()
    
    txt = input('Enter a substring: ').upper()
    words = txt

    matches = []
    sentences = re.split(r'\.', txt)
    keyword = List1[0]
    pattern = keyword 
    re.compile(pattern)

    for sentence in sentences:
        if re.search(pattern, sentence):
            matches.append(sentence)

    print("Sentence matching the word (" + keyword + "):")
    for match in matches:
        print (match)

标签: pythonpython-3.xregex

解决方案


你不需要正则表达式:

List1 = ['Cappuccino','Café Latte','Expresso','Macchiato','Irish coffee']
         
for i in range(len(List1)):
    List1[i] = List1[i].upper()

txt = input('Enter a substring: ').upper()

matches = []
sentences = txt.splitlines()
keyword = List1[0]

for sentence in sentences:
    if keyword in sentence:
        matches.append(keyword)

print(f'Sentence matching the word (" + {keyword} + "):')
for match in matches:
    print (match)

示例输出:

Enter a substring: I want 1 Cappuccino.
Sentence matching the word (" + CAPPUCCINO + "):
CAPPUCCINO

推荐阅读