Python字符串列表转换为列表的字符串

2024-04-20 16:31:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图像这样转换字符串列表

['{"What is the purpose of a noun?":"To name something or someone."}', '{"What is the purpose of a verb?":"To show action"}']

像这样的口述清单

[{"What is the purpose of a noun?":"To name something or someone."}, {"What       is the purpose of a verb?":"To show action"}]  

这是txt文件中原始字符串的样子

{"What is the purpose of a noun?":"To name something or someone."}
{"What is the purpose of a verb?":"To show action in a sentence."}  

json模块不工作

a = []
with open("proans.txt",'r') as proans:
    #transform string in the txt file into list of string by \n
    pa = proans.read().split('\n')
    #iterate through the list of string, convert string to dict and put them                           
    #into a list
    for i in range(len(pa)):
        json_acceptable_string = pa[i].replace("\"", "'")
        ret_dict = json.loads(json_acceptable_string)
        a.append(ret_dict)  

我犯了这样的错误

ValueError: Expecting property name: line 1 column 2 (char 1)  

如何将这种类型的字符串列表转换为dict列表?谢谢


Tags: oroftheto字符串namejson列表
1条回答
网友
1楼 · 发布于 2024-04-20 16:31:01

去掉replace行:json_acceptable_string = ...。没有必要逃避引用。你知道吗

>>> lst = ['{"What is the purpose of a noun?":"To name something or someone."}', '{"What is the purpose of a verb?":"To show action"}']
>>> import json
>>> [json.loads(el) for el in lst]
[{u'What is the purpose of a noun?': u'To name something or someone.'}, {u'What is the purpose of a verb?': u'To show action'}]
>>> [json.loads(el.replace("\"", "'")) for el in lst]
Traceback (most recent call last):
  ...
ValueError: Expecting property name: line 1 column 2 (char 1)

类似于带有StringIO对象的原始代码的示例:

>>> proans = StringIO.StringIO("""{"What is the purpose of a noun?":"To name something or someone."}
... {"What is the purpose of a verb?":"To show action in a sentence."}""")
>>> pa = proans.read().split('\n')
>>> proans
['{"What is the purpose of a noun?":"To name something or someone."}', '{"What is the purpose of a verb?":"To show action in a sentence."}']
>>> for i in range(len(pa)):
...     print json.loads(pa[i])
...
{u'What is the purpose of a noun?': u'To name something or someone.'}
{u'What is the purpose of a verb?': u'To show action in a sentence.'}

相关问题 更多 >