字典字符串上的 Python ast.literal_eval 不起作用(语法错误:语法无效) [英] Python ast.literal_eval on dictionary string not working (SyntaxError: invalid syntax)

查看:86
本文介绍了字典字符串上的 Python ast.literal_eval 不起作用(语法错误:语法无效)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 JSON 数据处理数据集.但是,数据已写入文件而未进行解析.这意味着 Python 字典是作为字符串写入文件的,而不是将 JSON 对象作为字符串写入.

I am trying to process a dataset with JSON data. However, the data have been written on a file without being parsed. That means that a python dictionary is written in the file as a string instead of a JSON object as a string.

我找到了一个模块 (AST),它可以使用 ast.literal_eval 函数再次将字符串转换为字典.

I've found a module (AST) that will do the job to convert the string to a dictionary again using the ast.literal_eval function.

但是,我在某些情况下遇到了一个非常奇怪的错误:

However, I am getting a very strange error in some of the instances:

该代码从文本文件中读取并将以下内容应用于每一行:

The code reads from a text file and apply the following to each line:

ast.literal_eval(line.rstrip())

似乎有些字符不适用于 AST 模块.

It seems some of the characters are not ok with the AST module.

还需要记住,这种情况并非发生在所有数据集上,只是发生在某些实例上.

Need to recall as well that this is not happening with all the dataset, just with some instances.

有什么想法吗?

非常感谢.

推荐答案

尝试探索 json 包.将字符串转换为字典的更简洁、更标准的方式

Try exploring the json package. It is cleaner and more standard way of converting strings to dictionary

json.loads(inputStr) // Converts string -> dict
json.dumps(inputJson) // Converts dict -> string

希望这会有所帮助.干杯!

Hope this helps. Cheers!

这篇关于字典字符串上的 Python ast.literal_eval 不起作用(语法错误:语法无效)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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