我试图在将一个单词分成它的后缀和前缀(即语素或词缀)等成分之后得到一个列表。
我尝试使用re.findall
函数的正则表达式
(如下所示)
>>> import re
>>> affixes = ['meth','eth','ketone', 'di', 'chloro', 'yl', 'ol']
>>> word = 'dimethylamin0ethanol'
>>> re.findall('|'.join(affixes), word)
['di', 'meth', 'yl', 'eth', 'ol']
但是,我需要包含不匹配的部分。例如,上述示例需要输出:
['di', 'meth', 'yl', 'amin0', 'eth', 'an', 'ol']
有谁知道如何在列表中提取这些段?
答案 0 :(得分:4)
您可以使用re.split()
捕获“分隔符”:
In [1]: import re
In [2]: affixes = ['meth', 'eth', 'ketone', 'di', 'chloro', 'yl', 'ol']
In [3]: word = 'dimethylamin0ethanol'
In [4]: [match for match in re.split('(' + '|'.join(affixes) + ')', word) if match]
Out[4]: ['di', 'meth', 'yl', 'amin0', 'eth', 'an', 'ol']
这里的列表理解是过滤空字符串匹配。
答案 1 :(得分:1)
import re
affixes = ['meth','eth','ketone', 'di', 'chloro', 'yl', 'ol']
word = 'dimethylamin0ethanol'
# found = ['amin0', 'an', 'di', 'meth', 'yl', 'eth', 'ol']
found = re.findall('|'.join(affixes), word)
# not_found = [('', 'di'), ('', 'meth'), ('', 'yl'), ('amin0', 'eth'), ('an', 'ol')]
not_found = re.findall(r'(.*?)(' + '|'.join(affixes) + ')', word)
# We need to modify extract the first item out of each tuple in not_found
# ONLY when it does not equal "".
all_items = map(lambda x: x[0], filter(lambda x: x[0] != "", not_found)) + found
print all_items
# all_items = ['amin0', 'an', 'di', 'meth', 'yl', 'eth', 'ol']
假设:您的最终列表不需要特定订单。