2016-12-06 172 views
2

我试图在将单词分割为词的后缀和前缀(即词素或词缀)后得到一个列表。分割的正则表达式 - 将单词拆分为词素或词缀

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

有谁知道如何提取列表中的这些部分?

回答

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

假设:你的最终名单并不需要特定的顺序。

相关问题