簡體   English   中英

考慮到空格,如何將列表中的精確字符串匹配到更大的字符串?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM