2017-05-25 12 views
1

名前、場所などとして、タイトルのという文字列のリストがあります。リストから抽出して、それらが近くにある場合は連結したい近くの単語は倍数です)。見つかった名前はすべてnamesのリストに挿入する必要があります。文字列のリスト内のタイトルを抽出して連結する

import re 
from itertools import tee, islice, chain, izip 

l = ['hello', 'John', 'how', 'are', 'you', 'The', 'White', 'House', 'cat'] 

def iter_next(some_iterable): 
    items, nexts = tee(some_iterable, 2) 
    nexts = chain(islice(nexts, 1, None), [None]) 
    return izip(items, nexts) 

names = [] 
for word, nxt in iter_next(l): 
    if word is not None and word.istitle(): 
     names.append(word) 
     if nxt is not None and nxt.istitle(): 
      names.append(word + ' ' + nxt) 
print names 

これらは結果です。

Results: 
['John', 'The', 'The White', 'White', 'White House', 'House'] 
Desired Results: 
['John', 'The', 'White ', 'House', 'The White House'] 

EDIT1: 彼らは(str.istitle付き)タイトルであり、彼らは、デフォルトで順序付けられたリストの近づくいる場合、私は言葉を連結します。

'you', 'The', 'White', 'House', 'cat' -> 'The White House' 
+1

申し訳ありません違う説明ができますか? –

+0

問題の説明に編集を追加しました。 – user6542453

答えて

4

あなたはstr.istitleを使用してグループへitertools.groupbyあなたのアイテムを使用することができます。 は、グループ内の項目で新しいリストを拡張し、グループ長が1より大きい場合を追加グループ項目に参加しました:私はあなたがそれらを連結な状態を理解していない

from itertools import groupby 

l = ['hello', 'John', 'how', 'are', 'you', 'The', 'White', 'House', 'cat'] 
names = [] 
for k, g in groupby(l, lambda x: x.istitle()): 
    if k: 
     g = list(g) 
     names.extend(g) 
     if len(g) > 1: 
      names.append(' '.join(g)) 

print(names) 
# ['John', 'The', 'White', 'House', 'The White House'] 
関連する問題