【问题标题】:Python - Search for a match for a word in a list of words in a string [closed]Python - 在字符串中的单词列表中搜索单词的匹配项[关闭]
【发布时间】:2021-02-23 09:28:45
【问题描述】:

我有一个这样的字符串:

text = "The best language in the word is $python at now"

以及要搜索的单词列表:

keywords = ["PYTHON","PHP","JAVA","COBOL","CPP","VB","HTML"]

如何获得“PYTHON”作为结果?

【问题讨论】:

  • $python 是如何与 PYTHON 匹配的?
  • @SreeramTP - 显然,即使是二进制计算也承认 python 是世界上最好的语言
  • @SreeramTP 因为单词前面可以有符号
  • 你可以使用这个:res = [elt for elt in keywords if elt.lower() in text.lower()]; print(res) 其中res 将是所有匹配单词的列表。

标签: python string-matching


【解决方案1】:

在 python 中,您可以使用in 运算符轻松检查一个字符串是否包含另一个字符串。

只需检查每个关键字的字符串,并记住使大小写相同。

你可以用一行

[print(x) for x in keywords if x in text.upper()]

或多个

for x in keywords:
    if x in text.upper():
        print(x)

在您的情况下,以下示例将输出PYTHON

text     = "The best language in the word is $python at now"
keywords = ["PYTHON","PHP","JAVA","COBOL","CPP","VB","HTML"] 

[print(x) for x in keywords if x in text.upper()] #PYTHON

祝你有美好的一天。

编辑

正如 Malo 所指出的,我可能会更好地将输出传递给变量,然后再打印它。

text     = "The best language in the word is $python at now"
keywords = ["PYTHON","PHP","JAVA","COBOL","CPP","VB","HTML"] 

matches  = [x for x in keywords if x in text.upper()]

for x in matches: print(x) # PYTHON

【讨论】:

  • print(x) 返回None。尝试执行此操作:lst = [print(x) for x in keywords if x in text.upper()]; print(lst)
  • [x for x in keywords if x in text.upper()] 直接返回匹配词列表。
【解决方案2】:

这段代码对我有用,但你必须在python之前去掉$

text = "The best language in the word is python at now"

keywords = ["PYTHON","PHP","JAVA","COBOL","CPP","VB","HTML"]

upper_text = text.upper()

ar_text = upper_text.split()

for word in keywords:
    if word in ar_text:
        print(word)

【讨论】:

  • 如果你没有拆分upper_text,你不需要从字符串if word in upper_text中删除任何东西就足够了
  • 好。只是ar_text不需要拆分。
【解决方案3】:

这将使用 find 检查是否有任何列表项在字符串中(不区分大小写,因为这是您要问的):

results = []
for keyword in keywords:
    if text.lower().find(keyword.lower()) != -1:
        results.append(keyword)

print(results)

【讨论】:

    猜你喜欢
    • 2011-10-18
    • 1970-01-01
    • 2018-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-08
    • 2021-09-14
    • 1970-01-01
    相关资源
    最近更新 更多