2016-06-07 35 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]]))