我如何在python中将字符串转换为元组

时间:2018-08-27 10:57:23

标签: python tuples

我已经从下面给出的csv_file中读取了一个字符串

"('Who is Shaka Khan?',{'entities': [(7, 17, 'PERSON')]})," 

当我遍历它时,我得到的每个字符为:

('(', "'", 'W', 'h', 'o', ' ', 'i', 's', ' ', 'S', 'h', 'a', 'k', 'a', ' ', 'K', 'h', 'a', 'n', '?', "'", ',', '{', "'", 'e', 'n', 't', 'i', 't', 'i', 'e', 's', "'", ':', ' ', '[', '(', '7', ',', ' ', '1', '7', ',', ' ', "'", 'P', 'E', 'R', 'S', 'O', 'N', "'", ')', ']', '}', ')', ',') 

但是我需要将其以元组形式存储,因此当我对其进行迭代时,我可以得到如下所示的输出

 Who is Shaka Khan?

{'entities': [(7, 17, 'PERSON')]} 

我如何在python中做到这一点?

4 个答案:

答案 0 :(得分:0)

使用ast.literal_eval将字符串转换为元组。

>>> s = "('Who is Shaka Khan?',{'entities': [(7, 17, 'PERSON')]})," 
>>> import ast
>>> t = ast.literal_eval(s)
>>> t[0]
('Who is Shaka Khan?', {'entities': [(7, 17, 'PERSON')]})
>>> t[0][0]
'Who is Shaka Khan?'
>>> t[0][1]
{'entities': [(7, 17, 'PERSON')]}

(可选)您可以将其转换为字典以便于访问

>>> d = dict(ast.literal_eval(s))
>>> d['Who is Shaka Khan?']
{'entities': [(7, 17, 'PERSON')]}

答案 1 :(得分:0)

使用literal_eval

In [87]: from ast import literal_eval

In [88]: literal_eval("('Who is Shaka Khan?',{'entities': [(7, 17, 'PERSON')]}),")
Out[88]: (('Who is Shaka Khan?', {'entities': [(7, 17, 'PERSON')]}),)

答案 2 :(得分:0)

您可以使用ast.literal_eval

import ast
a = ast.literal_eval("('Who is Shaka Khan?',{'entities': [(7, 17, 'PERSON')]}),")
print(a[0][1])

输出

{'entities': [(7, 17, 'PERSON')]}

答案 3 :(得分:-1)

  

您必须使用元组功能,但它必须事先是一个列表

示例:

l = [4,5,6]
tuple(l)
  

退货       (4、5、6)