2016-06-07 70 views
0

我是python的新用戶。我有這樣Python - >組織列表文本文件

NEW YORK ....... from  
31 Chatty, Seager Aarhaus  
Atlas, Jones Abertham   
Polly, Manning Antwerpen   
Amazon, Brittle Belchental  
LONDON ........ for   
31 Park Dattemroed  
Eleanor, Mallett Civeta Naples  
3 Aurora Frigate Ljubljana 

爲.txt格式列表(和.csv),我想有

NEW YORK ....... from 31 Chatty, Seager Aarhaus  
NEW YORK ....... from Atlas, Jones Abertham   
NEW YORK ....... from Polly, Manning Antwerpen  
NEW YORK ....... from Amazon, Brittle Belchental  
LONDON ........ for 31 Park Dattemroed   
LONDON ........ for Eleanor, Mallett Civeta Naples  
LONDON ........ for 3 Aurora Frigate Ljubljana 

我嘗試使用正則表達式,但我不能獲得滿意的結果。

我不知道是否有辦法做到這一點。

+2

「*我不知道是否有辦法做到這一點。*」 - 就在這裏。事實上,有很多方法可以做到這一點。哪一種方法取決於許多你沒有分享的因素。也許你可以告訴我們你到目前爲止所嘗試過的東西,以及它如何工作或沒有。然後我們可以建立在你的工作上。 –

+1

爲什麼'LONDON'後面有8個點,但是'NEW YORK'後面只有7個點?如果你想使用正則表達式,你可能需要一個[常規語言](http://stackoverflow.com/questions/6718202/what-is-a-regular-language) –

+0

謝謝,我試圖按照大寫字母話。我應該發過來,但我什麼都沒有。 –

回答

1

如果城市行總是有.....可以使用GROUPBY:

from itertools import groupby 

with open(your_file) as f: 
    grps = groupby(f, key=lambda line: "......." in line) 
    for k,v in grps: 
     if k: 
      head = next(v).strip() 
      print("\n".join(["{} {}".format(head, line.strip()) for line in next(grps)[1]])) 

哪個會給你:

NEW YORK ....... from 31 Chatty, Seager Aarhaus 
NEW YORK ....... from Atlas, Jones Abertham 
NEW YORK ....... from Polly, Manning Antwerpen 
NEW YORK ....... from Amazon, Brittle Belchental 
LONDON ........ for 31 Park Dattemroed 
LONDON ........ for Eleanor, Mallett Civeta Naples 
LONDON ........ for 3 Aurora Frigate Ljubljana 
+0

謝謝!我試圖按大寫字母組織。但在你的幫助下,我做到了 –

+0

我剛剛意識到,當我使用「.write」而不是打印,保存在外部文件中時,出現了問題。節目不明白下一行是否有點並且給我: '紐約.......來自31 Chatty,Seager Aarhaus 紐約.......來自阿特拉斯,Jones Abertham 紐約.......來自Polly,曼寧安特衛普 紐約.......來自亞馬遜,脆弱Belchental倫敦........ 31 Park Dattemroed 倫敦........對於埃莉諾,馬列萊維塔那不勒斯 倫敦........爲3極光護衛艦盧布爾雅那「 –

3

這是一個程序,打印您需要的輸出:

with open('x.in') as input_file: 
    for line in input_file: 
     line = line.rstrip() 
     if '....' in line: 
      city = line 
      continue 
     print (city, line) 

結果:

NEW YORK ....... from 31 Chatty, Seager Aarhaus 
NEW YORK ....... from Atlas, Jones Abertham 
NEW YORK ....... from Polly, Manning Antwerpen 
NEW YORK ....... from Amazon, Brittle Belchental 
LONDON ........ for 31 Park Dattemroed 
LONDON ........ for Eleanor, Mallett Civeta Naples 
LONDON ........ for 3 Aurora Frigate Ljubljana 
+0

簡單,pythonic,不需要導入任何重要任務。 –

0

謝謝!其實,我試圖按大寫字母組織。通過改變帕德里克·坎寧安代碼,我這樣做

for line in Text: 
newline = re.sub('^([A-Z][A-Z]+[A-Z])', '\\1≈', line) 

≈是隻是一些顯示有一個大寫的單詞,然後

grps = groupby(f_, key=lambda line: "≈" in line) 
for k,v in grps: 
    if k: 
     head = next(v).strip() 
     print('\n'.join(['{} {}'.format(head, line.strip()) for line in next(grps)[1]]))