使用Python解析CSV /制表符分隔的txt文件

the*_*men 23 python csv parsing dictionary

我目前有一个CSV文件,在Excel中打开时,总共有5列.只有A列和C列对我有意义,其余列中的数据无关紧要.

从第8行开始,然后以7的倍数(即第8,15,22,29,36行等)工作,我希望用Python 2.7创建一个包含这些字段信息的字典.列A中的数据将是键(6位整数),列C中的数据是键的相应值.我试图在下面强调这一点,但格式不是最好的: -

    A        B      C          D
1                           CDCDCDCD  
2                           VDDBDDB
3
4
5
6
7  DDEFEEF                   FEFEFEFE
8  123456         JONES
9
10
11
12
13
14
15 293849         SMITH
Run Code Online (Sandbox Code Playgroud)

按照上面的说法,我希望从A7(DDEFEEF)中提取值作为我的字典中的一个键,并将"FEFEFEFE"作为相应的数据,然后在我的字典中添加另一个条目,跳到第15行,其中"2938495"是我的键和"史密斯"是各自的值.

有什么建议?源文件是.txt文件,其中的条目以制表符分隔.谢谢

澄清:

只是为了澄清,到目前为止,我已尝试过以下方面: -

import csv

mydict = {:}
f = open("myfile", 'rt')
reader = csv.reader(f)
    for row in reader:
        print row
Run Code Online (Sandbox Code Playgroud)

以上只是一次打印出所有内容.我确实尝试了"读取器中的行(7)",但这返回了一个错误.然后我研究了它并在下面进行了一次但是它既不起作用:

import csv
from itertools import islice

entries = csv.reader(open("myfile", 'rb'))
mydict = {'key' : 'value'}

for i in xrange(6):
    mydict['i(0)] = 'I(2)    # integers representing columns
    range = islice(entries,6)
    for entry in range:
        mydict[entries(0) = entries(2)] # integers representing columns
Run Code Online (Sandbox Code Playgroud)

Ray*_*ger 54

首先将文本转换为列表列表.这将解决解析部分:

lol = list(csv.reader(open('text.txt', 'rb'), delimiter='\t'))
Run Code Online (Sandbox Code Playgroud)

其余的可以使用索引查找完成:

d = dict()
key = lol[6][0]      # cell A7
value = lol[6][3]    # cell D7
d[key] = value       # add the entry to the dictionary
 ...
Run Code Online (Sandbox Code Playgroud)


小智 7

虽然其他解决方案没有任何问题,但您可以使用python优秀的库熊猫简化并大大提升您的解决方案.

Pandas是一个用于处理Python数据的库,是许多数据科学家的首选.

Pandas有一个简化的CSV接口来读取和解析文件,可以用来返回一个字典列表,每个字典包含一行文件.键将是列名称,值将是每个单元格中的值.

在你的情况下:

    import pandas

    def create_dictionary(filename):
        my_data = pandas.DataFrame.from_csv(filename, sep='\t', index_col=False)
        # Here you can delete the dataframe collumns you dont want!
        del my_data['B']
        del my_data['D']
        # ...
        # Now you transform the DataFrame to a list of dictionaries
        list_of_dicts = [item for item in my_data.T.to_dict().values()]
        return list_of_dicts

# Usage:
x = create_dictionary("myfile.csv")
Run Code Online (Sandbox Code Playgroud)