我正在以
格式从网页的html中提取列表lst = '["a","b","c"]' # (type <str>)
上面的数据类型是 str ,我希望它转换为python 列表类型,这样的事情
lst = ["a","b","c"] #(type <list>)
我可以通过
获得上述内容lst = lst[1:-1].replace('"','').split(',')
但由于a,b&amp; c的实际值非常长且复杂(包含长html文本),我无法依赖上述方法。
我也试过用json模块并使用json.loads(lst)
,这给出了以下异常
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/json/__init__.py", line 339, in loads
return _default_decoder.decode(s)
File "/usr/local/lib/python2.7/json/decoder.py", line 364, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/local/lib/python2.7/json/decoder.py", line 382, in raw_decode
raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded
在Python中以任何方式转换为列表?
编辑:列表的实际值是:
['reqlistitem.no','reqlistitem.applyonlinejobdesc','reqlistitem.no','reqlistitem.referjobdesc','reqlistitem.applyemailsubjectapplication','reqlistitem.applyemailjobdesc','reqlistitem.no','reqlistitem.addedtojobcart','reqlistitem.displayjobcartactionjobdesc','reqlistitem.shareURL','reqlistitem.title','reqlistitem.shareable','reqlistitem.title','reqlistitem.contestnumber','reqlistitem.contestnumber','reqlistitem.description','reqlistitem.description','reqlistitem.primarylocation','reqlistitem.primarylocation','reqlistitem.otherlocations','reqlistitem.jobschedule','reqlistitem.jobschedule','reqlistitem.jobfield','reqlistitem.jobfield','reqlistitem.displayreferfriendaction','reqlistitem.no','reqlistitem.no','reqlistitem.applyonlinejobdesc','reqlistitem.no','reqlistitem.referjobdesc','reqlistitem.applyemailsubjectapplication','reqlistitem.applyemailjobdesc','reqlistitem.no','reqlistitem.addedtojobcart','reqlistitem.displayjobcartactionjobdesc','reqlistitem.shareURL','reqlistitem.title','reqlistitem.shareable']
答案 0 :(得分:2)
我认为您正在寻找literal_eval
:
import ast
string = '["a","b","c"]'
print ast.literal_eval(string) # ['a', 'b', 'c']
答案 1 :(得分:1)
示例字符串中的问题是单引号。 JSON标准需要双引号。
如果您将单引号更改为双引号,它将起作用。一种简单的方法是使用str.replace()
:
import json
s = "['reqlistitem.no','reqlistitem.applyonlinejobdesc','reqlistitem.no']"
json.loads(s.replace("'", '"'))
#[u'reqlistitem.no', u'reqlistitem.applyonlinejobdesc', u'reqlistitem.no']