Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 如何从给定的句子中提取较长的字符串并忽略子字符串?_Python 3.x_String Matching - Fatal编程技术网

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']

不要提供外部链接,请使用文本