我的文件格式如下:
Berlin, Germany
New Delhi , India
New York , USA
Mumbai , India
Seattle, USA
我需要解析文件并将输出打印为
Germany : Berlin
India: New Delhi , Mumbai
USA: New York, Seattle
我写了一个代码:
enter code here:
def check():
datafile=open('logfile.py','rU')
found=False
for line in datafile:
if 'India' in line:
lines=line.split()
print("India"+":"+lines[0])
if 'Germany' in line:
lines=line.split()
print("Germany"+":"+lines[0])
if 'USA' in line:
lines=line.split()
print("USA"+":"+lines[0])
datafile.close()
check()
此代码给出的输出为:
Germany:Berlin
India:NewDelhi
USA:NewYork
India:Mumbai
USA:Seattle
请帮忙。
另一种方法是使用defaultdict
fromcollections
实现此目的:
from collections import defaultdict
def check():
d = defaultdict(list)
with open('logfile.py', 'rU') as datafile:
for line in datafile:
data = line.split(',')
d[data[1].strip()].append(data[0].strip())
return d
res = check()
for k, v in res.items():
print("{} : {}".format(k, ', '.join(v)))
输出:
India : New Delhi, Mumbai
Germany : Berlin
USA : New York, Seattle
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句