且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用正则表达式删除python中的逗号,括号?

更新时间:2023-02-17 22:12:48

使用 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`.