2017-05-25 24 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']