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

2024-05-16 16:35:39 发布

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

我有一张单子

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

我必须从用户处获取输入句子,如果列表1中的任何单词匹配,则应返回该列表1中的字符串以及一些图例

示例:输入输入字符串: 用户输入: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)

Tags: inretxtforkeywordsentencepatternmatches
3条回答

我建议根据关键字列表构建一个regex替换:

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

您不需要正则表达式:

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

相关问题 更多 >