Python - 在字符串的单词列表中搜索单词的匹配项
Python - Search for a match for a word in a list of words in a string
我有这样的字符串:
text = "The best language in the word is $python at now"
以及要搜索的单词列表:
keywords = ["PYTHON","PHP","JAVA","COBOL","CPP","VB","HTML"]
如何得到“PYTHON”作为结果?
这段代码对我有用,但你必须去掉 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)
在 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
这将使用 find 来检查字符串中是否有任何列表项(不区分大小写,因为这是你要问的):
results = []
for keyword in keywords:
if text.lower().find(keyword.lower()) != -1:
results.append(keyword)
print(results)
我有这样的字符串:
text = "The best language in the word is $python at now"
以及要搜索的单词列表:
keywords = ["PYTHON","PHP","JAVA","COBOL","CPP","VB","HTML"]
如何得到“PYTHON”作为结果?
这段代码对我有用,但你必须去掉 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)
在 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
这将使用 find 来检查字符串中是否有任何列表项(不区分大小写,因为这是你要问的):
results = []
for keyword in keywords:
if text.lower().find(keyword.lower()) != -1:
results.append(keyword)
print(results)