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



我有一个列表

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)

您不需要regex:

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

我建议基于关键字列表构建正则表达式替换:

List1 = ['Cappuccino','Café Latte','Expresso','Macchiato ','Irish coffee ']
regex = r'b(' + '|'.join(List1) + r')'
sentence = 'I want 1 Cappuccino'
matches = re.findall(regex, sentence)
if matches:
print('Found keywords: ' + ','.join(matches))  # Found keywords: Cappuccino
List1 = ['Cappuccino', 'Café Latte', 'Expresso', 'Macchiato', 'Irish coffee']
inp = 'I want 1 Café Latte'
x = [i for i, x in enumerate('#'.join(List1).upper().split('#')) if x in inp.upper()]
print(f"item: {List1[x[0]]}" if x else "item: nothing :(")

输出:

item: Café Latte