Python解析文件中的行

时间:2015-11-27 21:07:44

标签: python list parsing

python新手。我逐行阅读文件:

with open("graph.txt", "r") as f:
    comList = f.readlines()
    print(comList)
    edge_u = [x[0] for x in comList]
    edge_v = [x[1] for x in comList]

graph.txt有:

  

[(0,7),(1,9),(1,9),(2,0)]

     

[(2,1),(2,1),(3,6)]

我原以为readlines会逐行解析文件,因此会将文本解析为列表列表。但它将其解析为字符串列表。因此我无法执行其他两个操作。试图打印edge_u并了解它的解析。怎么处理这个?感谢。

4 个答案:

答案 0 :(得分:4)

你可以试试这个:

import ast

with open("test.txt", "r") as f:
    for line in f:
        li = ast.literal_eval(line)
        edge_u = [x[0] for x in li]
        edge_v = [x[1] for x in li]

答案 1 :(得分:1)

file.readlines([size])返回大小字节值的行或所有行作为字符串列表。如果你想解析这个文件,我相信你想要的是json。

from json import loads

with open('graph.txt', 'r') as fob:
    comList = [loads(line) for line in fob]

edge_u = [x[0] for x in comList]
edge_v = [x[1] for x in comList]

答案 2 :(得分:0)

你可以使用eval,但要小心不要抓住特殊的东西:

In [1]: tmp = eval("[(0, 7), (1, 9), (1, 9), (2, 0)]")
In [2]: tmp
Out[2]: [(0, 7), (1, 9), (1, 9), (2, 0)]

否则,您必须手动解析字符串(这实际上是更好的解决方案)。

答案 3 :(得分:0)

根据建议,您可以使用eval

with open("graph.txt","r") as f:
        lines = f.readlines()
        comList = list(map(eval, lines))
        print(type(comList), comList)
        edge_u = [x[0] for x in comList]
        edge_v = [x[1] for x in comList]

print(type(edge_u), edge_u)
print(type(edge_v), edge_v)

产生

<class 'list'> [[(0, 7), (1, 9), (1, 9), (2, 0)], [(0, 7), (1, 9), (1, 9), (2, 0)]]
<class 'list'> [(0, 7), (0, 7)]
<class 'list'> [(1, 9), (1, 9)]