2016-12-06 3 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'] 

想定:最終リストには特定の注文は必要ありません。

関連する問題