删除列表中的字符串括号或将字符串转换为另一种数据类型

时间:2014-05-22 15:45:23

标签: python string list

我们需要将列表设置为某种格式以便进一步解析。现在它看起来像这样:

sentence = ['("Senators","NNS"),("and","CC"),("a","DT"),("good","JJ"),("teacher","NN"),("believe","VBZ"),("in","IN")']

为了使解析器正常工作,我们需要的是:

sentence = [("Senators","NNS"),("and","CC"),("a","DT"),("good","JJ"),("teacher","NN"),("believe","VBZ"),("in","IN")]

我们需要摆脱单个括号;任何想法?

1 个答案:

答案 0 :(得分:1)

使用ast模块'literal_eval()是一种方法:

>>> data = ['("Senators","NNS"),("and","CC"),("a","DT"),("good","JJ"),("teacher","NN"),("believe","VBZ"),("in","IN")']
>>> import ast
>>> inner = ast.literal_eval(data[0])
>>> list(inner)
[('Senators', 'NNS'), ('and', 'CC'), ('a', 'DT'), ('good', 'JJ'), ('teacher', 'NN'), ('believe', 'VBZ'), ('in', 'IN')]