Python: 使用 Ast 模块解析文本文件中的字符串时出错

Python: error parsing strings from text file with Ast module

我有一个包含以下两个字符串的文本文件 (.txt)(这是一个较大文件的片段,其中所有字符串都具有相同的格式):

["('a', '1')", "('b', '2')"]
["('c', '3')", "('d', '4')"]

我正在使用下面的代码来解析文本文件中的字符串,以便我可以访问每个元素以进行数据分析。如果我将其声明为变量,则该代码适用于该字符串,例如:

string = ["('c', '3')", "('d', '4')"]

但代码不适用于文本文件:

import ast

text_file = open('text_file.txt', 'r')

for string in text_file:
    parsed = list([ast.literal_eval(x) for x in text_file])
    print parsed

我希望得到:

[('a', '1'), ('b', '2')]
[('c', '3'), ('d', '4')]

但我收到以下错误:

Traceback (most recent call last):
  File "test.py", line 8, in <module>
    parsed = list([ast.literal_eval(x) for x in string])
  File "/usr/local/Cellar/python/2.7.8_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ast.py", line 49, in literal_eval
    node_or_string = parse(node_or_string, mode='eval')
  File "/usr/local/Cellar/python/2.7.8_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ast.py", line 37, in parse
    return compile(source, filename, mode, PyCF_ONLY_AST)
  File "<unknown>", line 1
    [
    ^
SyntaxError: unexpected EOF while parsing

您需要对字符串本身应用 ast.literal_eval 函数。您不需要遍历字符串的内容。

with open('file') as f:
    for string in f:
        parsed = ast.literal_eval(string.strip())
        print parsed

输出:

["('a', '1')", "('b', '2')"]
["('c', '3')", "('d', '4')"]

import re
with open('file') as f:
    for string in f:
        print re.findall(r"\('([^']*)',\s*'([^']*)'\)", string)

输出:

[('a', '1'), ('b', '2')]
[('c', '3'), ('d', '4')]
import ast 

text_file = open('text_file.txt', 'r')

for string in text_file:
    print ast.literal_eval(string)