[英]How do I match exact strings from a list to a larger string taking white spaces into account?
我有一个很大的字符串列表,我想检查一个字符串是否出现在更大的字符串中。 该列表包含一个单词的字符串和多个单词的字符串。 为此,我编写了以下代码:
example_list = ['pain', 'chestpain', 'headache', 'sickness', 'morning sickness']
example_text = "The patient has kneepain as wel as a headache"
emptylist = []
for i in example_text:
res = [ele for ele in example_list if(ele in i)]
emptylist.append(res)
然而,这里的问题是“痛苦”也被添加到空列表中,它不应该,因为我只希望在与文本完全匹配的情况下添加 example_list 中的某些内容。 我也尝试使用集合:
word_set = set(example_list)
phrase_set = set(example_text.split())
word_set.intersection(phrase_set)
然而,这将 op 'morning disease' 分为'morning' 和 'sickness'。 有谁知道解决这个问题的正确方法是什么?
使用 PyParsing:
import pyparsing as pp
example_list = ['pain', 'chestpain', 'headache', 'sickness', 'morning sickness']
example_text = "The patient has kneepain as wel as a headache morning sickness"
list_of_matches = []
for word in example_list:
rule = pp.OneOrMore(pp.Keyword(word))
for t, s, e in rule.scanString(example_text):
if t:
list_of_matches.append(t[0])
print(list_of_matches)
其中产生:
['headache', 'sickness', 'morning sickness']
成员在这篇文章中已经提供了很好的例子。
我使matching_text更具挑战性,因为它不止一次地出现了疼痛。 我还希望了解更多有关比赛位置开始位置的信息。 我最终得到了以下代码。
我研究了以下句子。
"The patient has not only kneepain but headache and arm pain, stomach pain and sickness"
import re
from collections import defaultdict
example_list = ['pain', 'chestpain', 'headache', 'sickness', 'morning sickness']
example_text = "The patient has not only kneepain but headache and arm pain, stomach pain and sickness"
TruthFalseDict = defaultdict(list)
for i in example_list:
MatchedTruths = re.finditer(r'\b%s\b'%i, example_text)
if MatchedTruths:
for j in MatchedTruths:
TruthFalseDict[i].append(j.start())
print(dict(TruthFalseDict))
以上给了我以下输出。
{'pain': [55, 69], 'headache': [38], 'sickness': [78]}
您应该能够使用使用字边界的正则表达式
>>> import re
>>> [word for word in example_list if re.search(r'\b{}\b'.format(word), example_text)]
['headache']
这将不匹配'pain'
'kneepain'
'pain'
中的'kneepain'
因为它不以单词边界开头。 但它会正确匹配包含空格的子字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.