数据从文本文件读取到python中的两个列表

时间:2015-09-25 22:12:36

标签: python

我的文本文件格式为:

apple      very healthy
orange     tangy and juicy
banana     yellow in color and yummy

我需要创建两个列表:

l1 = ['apple','orange','banana']
l2=['very healthy','tangy and juicy','yellow in color and yummy']

或将值转换为字典:

d1={'apple':'very healthy','orange':'tangy and juicy','banana':'yellow in color and yummy'}

文件中的前两列用制表符分隔。

我尝试使用以下代码将其更改为两个列表,然后将其转换为字典:

l1=[]
l2=[]
d={}
read_file=open('edges.txt','r')
split= [line.strip() for line in read_file]
for line in split:
    l1.append(line.split('\t')[0])
    l2.append(line.split('\t')[1:])
d=dict(zip(l1,l2))
print d

我得到一些不正确的值。我是python的新手..

5 个答案:

答案 0 :(得分:1)

确保您的文本文件包含这些值之间的选项卡,我从这里复制的内容有空格。

TEXTFILE:

apple   very healthy
orange  tangy and juicy
banana  yellow in color and yummy

您的脚本输出:

  

{'orange':['气味多汁'],'苹果':['非常健康'],'香蕉':['黄色和美味']}

答案 1 :(得分:0)

问题可能是文件的列实际上并没有被制表符分隔,而是由多个空格分隔(事实上,"文本文件格式"你发布了不使用标签)。解决此问题的一种方法是:

l1=[]
l2=[]
d={}
read_file=open('edges.txt','r')
split= [line.strip() for line in read_file]
for line in split:
    l1.append(line.split('  ')[0].strip())
    l2.append('  '.join(line.split('  ')[1:]).strip())
d=dict(zip(l1,l2))
print d

如果使用至少两个空格,则会将两列分开。但是,如果您实际使用制表符,则无法使用,在这种情况下,您应该使用原始代码。 并且,如果这些值中没有一个(例如tangy and juicyvery healthy)在其中的一行中有两个空格,则可以替换

'  '.join(line.split('  ')[1:]).strip()

使用

line.split('  ')[1].strip()

答案 2 :(得分:0)

line.split('\t')会返回一个列表,line.split('\t')[0]会返回该列表的第一个元素(' apple',' orange',' banana&# 39。)

l2.append(line.split('\t')[1:]会返回一个列表,因为[1:]slice。也许你想要l2.append(line.split('\t')[1]代替?

我无法拒绝重写代码:

d={}
for line in open('edges.txt','r'):
    split = line.strip().split('\t', 1)
    d[split[0]] = split[1]
print d

答案 3 :(得分:0)

导入重新

d = {}
with open('data') as f:
    for line in f:
        mobj =  re.match('(\w+)\s+(.*)',line)
        key, value = mobj.groups()
        d[key] = value


for k,v in d.items():
    print(k,"   ", v )

<强>输出

香蕉黄色和美味

苹果非常健康

橙色浓郁而多汁

答案 4 :(得分:0)

如果你的文本文件实际上是固定宽度(即包含空格而不是制表符),你只需使用索引来分割前10个字符(作为字典中的键)和第11个字符(如价值观。)

fruits = {line[:10].strip(): line[10:].strip() for line in read_file}

This question在解析更复杂的固定宽度文本文件时有一些答案;你也可以使用pandas.read_fwf

相关问题