python - 获取用户输入的句子/字符串并比较列表中的项目,如果句子中的关键字与列表项匹配,则返回列表条目
问题描述
我有一个清单
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)
解决方案
你不需要正则表达式:
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
推荐阅读
- javascript - 如何让 MaterialUI XGrid 过滤器通过 renderCell 参数而不是后端数据进行过滤?
- css - 在 Bootstrap 5 中单击时,如何使导航栏切换为显示导航栏
- python - 为什么 nmap 在扫描端口时给我的结果与 Python 不同?
- php - 如何为 PHP 8 设置合适的 Apache 版本
- terraform - GKE Terraformed 集群发布通道设置
- r - 绘制 unicode 字符 Windows OS R
- python - 单击图像旁边的
- javascript - 递归函数 - 超出最大调用堆栈大小
- python - 切片类似于 numpy np.ix_ 的 2D 张量
- flutter - 在 Flutter 应用中使用 Stream 填充 TextEditingController