如何使用正则表达式删除python中的逗号,括号? [英] How to remove commas, brackets in python using regular expression?
问题描述
这些是我的文本文件(例如:abc.doc)的内容:
{'data': [{'name': 'abc'},{'name': 'xyz'}]}
在python中打开文件后;如何删除所有括号、引号和逗号.最终输出应该是:
数据:名称:abc名称:xyz
使用 ast.literal_eval()
把它变成一个python结构,然后打印值:
with open(r'd:\output1.doc', 'r') 作为输入文件:inputstring = inputfile.read()数据 = ast.literal_eval(inputstring)对于关键,data.items() 中的子列表:打印 '{}:'.format(key)对于子列表中的 subdict:对于键,subdict.items() 中的值:print('{}:{}'.format(key, value))
对于您导致的示例:
<预><代码>>>>inputstring = "{'data': [{'name': 'abc'},{'name': 'xyz'}]}">>>进口AST>>>数据 = ast.literal_eval(inputstring)>>>对于关键,data.items() 中的子列表:... 打印 '{}:'.format(key)... 对于子列表中的 subdict:...对于键,subdict.items() 中的值:... 打印 '{}:{}'.format(key, value)...数据:名称:abc名称:xyz但是:如果您是从 Facebook API 获得的,那么您就错误地转录了格式.Facebook API 为您提供 JSON 数据,它使用 双引号 ("
) 代替:
{"data": [{"name": "abc"},{"name": "xyz"}]}
在这种情况下,您应该使用 json
库一个> Python 自带的:
导入json数据 = json.loads(inputstring)# 处理方式与上述相同.
如果您有文件名,则可以使用以下命令让库直接从文件中读取:
data = json.load(filename) # 注意,`load` 后面没有 `s`.
These are the contents of my text file (eg:abc.doc):
{'data': [{'name': 'abc'},{'name': 'xyz'}]}
After opening the file in python; how do i remove all the brackets, quotes and commas. The final output should be:
data:
name:abc
name:xyz
Use ast.literal_eval()
to turn it into a python structure, then print the values:
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))
For your example that results in:
>>> 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
However: If you got this from the Facebook API, then you transcribed the format incorrectly. The Facebook API gives you JSON data, which uses double quotes ("
) instead:
{"data": [{"name": "abc"},{"name": "xyz"}]}
in which case you should use the json
library that comes with Python:
import json
data = json.loads(inputstring)
# process the same way as above.
If you have a filename, you can ask the library to read straight from the file using:
data = json.load(filename) # note, no `s` after `load`.
这篇关于如何使用正则表达式删除python中的逗号,括号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!