Python:使用 Ast 模块解析文本文件中的字符串时出错 [英] Python: error parsing strings from text file with Ast module

查看:30
本文介绍了Python:使用 Ast 模块解析文本文件中的字符串时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a text file (.txt) with the following two strings as so (this is a snippet of a larger file where all strings have the same format):

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

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

I am using the below code to parse the strings in the text file so that I can access each element for data analysis. The code works for the string if I declare it as a variable, such as:

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

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

但是代码对文本文件不起作用:

But the code does not work for the text file:

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 函数.您不需要遍历字符串的内容.

You need to apply ast.literal_eval function on the string itself. You don't need to iterate over the contents of the string.

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')]

这篇关于Python:使用 Ast 模块解析文本文件中的字符串时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆