Python 3.x 如何从给定的句子中提取较长的字符串并忽略子字符串?
我有一个字符串列表和一个句子,如下所示:Python 3.x 如何从给定的句子中提取较长的字符串并忽略子字符串?,python-3.x,string-matching,Python 3.x,String Matching,我有一个字符串列表和一个句子,如下所示: list_of_strings=["skin allergy","hair loss","allergy","hair", "skin"] sentence="She experienced skin allergy and hair loss after using it for 2-3 weeks" 我想将列表\u字符串与句子匹配,并仅将输出打印为较长的短语(忽略子字符串): 我这样写的:但这会提取所有匹配的内容。使用正则表达式 Ex: impo
list_of_strings=["skin allergy","hair loss","allergy","hair", "skin"]
sentence="She experienced skin allergy and hair loss after using it for 2-3 weeks"
我想将列表\u字符串
与句子
匹配,并仅将输出打印为较长的短语(忽略子字符串):
我这样写的:但这会提取所有匹配的内容。使用正则表达式
Ex:
import re
list_of_strings=["skin allergy","hair loss","allergy","hair", "skin"]
sentence="She experienced skin allergy and hair loss after using it for 2-3 weeks"
pattern = re.compile(r"(\b" + "|".join(list_of_strings) + r")\b")
m = pattern.findall(sentence)
print(m)
['skin allergy', 'hair loss']
输出:
import re
list_of_strings=["skin allergy","hair loss","allergy","hair", "skin"]
sentence="She experienced skin allergy and hair loss after using it for 2-3 weeks"
pattern = re.compile(r"(\b" + "|".join(list_of_strings) + r")\b")
m = pattern.findall(sentence)
print(m)
['skin allergy', 'hair loss']
不要提供外部链接,请使用文本