这些是我的文本文件(例如:abc.doc)的内容:
{'data': [{'name': 'abc'},{'name': 'xyz'}]}
在python中打开文件后;如何删除所有括号、引号和逗号。最终输出应该是:
data:
name:abc
name:xyz
用于ast.literal_eval()
将其转换为 python 结构,然后打印值:
with open(r'd:\output1.doc', 'r') as inputfile:
inputstring = inputfile.read()
data = ast.literal_eval(inputstring)
for key, sublist in data.items():
print '{}:'.format(key)
for subdict in sublist:
for key, value in subdict.items():
print('{}:{}'.format(key, value))
对于您的示例,结果为:
>>> inputstring = "{'data': [{'name': 'abc'},{'name': 'xyz'}]}"
>>> import ast
>>> data = ast.literal_eval(inputstring)
>>> for key, sublist in data.items():
... print '{}:'.format(key)
... for subdict in sublist:
... for key, value in subdict.items():
... print '{}:{}'.format(key, value)
...
data:
name:abc
name:xyz
但是:如果您是从 Facebook API 获得的,那么您转录的格式不正确。Facebook API 为您提供 JSON 数据,它使用双引号 ( "
) 代替:
{"data": [{"name": "abc"},{"name": "xyz"}]}
在这种情况下,您应该使用 Python 附带的json
库:
import json
data = json.loads(inputstring)
# process the same way as above.
如果您有文件名,则可以使用以下命令要求库直接从文件中读取:
data = json.load(filename) # note, no `s` after `load`.