用于将单词分割为语素或词缀的正则表达式

2024-04-26 07:47:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在把一个词分成后缀和前缀(即语素或词缀)等成分后得到一个列表。在

我尝试过使用正则表达式和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']

有人知道如何提取列表中的这些片段吗?在


Tags: 函数re列表后缀wordeth成分ol
2条回答

您可以使用^{}捕获“分隔符”:

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

这里的列表理解是过滤空字符串匹配。在

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

假设:您的最终列表不需要特定的顺序。在

相关问题 更多 >