简体   繁体   English

从文本文件的Python字典

[英]Python Dictionary from text file

Hello I have a file text that holds a sequence like this: 您好我有一个文件文本,其中包含如下序列:

TCA:DateIn,TimeIn,Content,Quantity,Company,TankerName,Country,PortFrom  
26/02/2013,15:00,Natural gas,30000,Linkers, Blue Ice, China,Shanghai
09/03/2013,06:30,Sugar,45000,Navigators,Lady Fish, Netherlands, Rotterdam 

how can I using dictionary, header name as keys(DateIn,TimeIn...) and the lines below the values display it into something like this, with the columns being separated by tabs rather than by commas: 我如何使用字典,标题名称作为键(DateIn,TimeIn ...),值下方的行显示为这样的类,其中列由制表符而不是逗号分隔:

TCA:TankerName Company      Country     DateIn        TimeIn     PortFrom     Content      Quantity
Blue Ice       Linkers      China       26/02/2013    15:00      Shanghai     NaturalGas   30000
Lady Fish      Navigators   Netherlands 09/03/2013    06:30      Rotterdam    Sugar        45000

I have tried many thing but that I can't problem is that I am not able to relate key with values. 我尝试了很多东西,但我不能解决的问题是我无法将键与值相关联。 I am currently using python 3.3.1 but if it works using another version no problem 我目前正在使用python 3.3.1,但如果它使用另一个版本没有问题

Thanks 谢谢

Have a look at the Python CSV module: 看看Python CSV模块:

http://docs.python.org/3.3/library/csv.html http://docs.python.org/3.3/library/csv.html

This will get you started: 这将让你开始:

import csv

with open('/tmp/ships.csv','r') as din:
    scsv=csv.reader(din)
    for i,row in enumerate(scsv):
        if i:
            for type,data in zip(header,row):
                d[type].append(data.strip())
        else:
            header=row
            d={item:[] for item in row}

print(d)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM