用Python解析文件

阿卡什(Akash)深

我的文件格式如下:

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

请帮忙。

爪子

另一种方法是使用defaultdictfromcollections实现此目的:

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] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章