我是python的新用户。我有一个.txt格式的列表(和.csv),像这样
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
我希望
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 :(得分:3)
这是一个打印所需输出的程序:
mysqladmin reload
结果:
with open('x.in') as input_file:
for line in input_file:
line = line.rstrip()
if '....' in line:
city = line
continue
print (city, line)
答案 1 :(得分: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
,您可以使用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]]))
答案 2 :(得分:0)
实际上,我试图按照大写字母组织。通过改变Padraic Cunningham代码,我做了这个
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]]))