用Python字符串列表中的括号替换双引号

时间:2018-06-19 17:26:29

标签: python string list text-processing naivebayes

这是我当前列表的格式:

["'There's no going back', 'pop'", "'Mark my words', 'pop'", "'This love will make you levitate', 'pop'", "'Like a bird, like a bird without a cage', 'pop'"]

我想将其转换为以下格式:

[('There\'s no going back', 'pop'), ('Mark my words', 'pop'), ('This love will make you levitate', 'pop'), ('Like a bird, like a bird without a cage', 'pop')]

所以我需要将输入字符串标记为元组。但是我不确定如何完成此操作,因为“”主要是一个字符串,因此它存在。

如果需要其他上下文,我将以上述格式抓取大量数据,并使用Naive Bayes分类器对其进行处理,我需要使用方括号格式。如果效率更高,我愿意尝试其他方法。

1 个答案:

答案 0 :(得分:2)

使用replacesplit

lst = ["'There's no going back', 'pop'", "'Mark my words', 'pop'", "'This love will make you levitate', 'pop'", "'Like a bird, like a bird without a cage', 'pop'"]

print([tuple(x.replace('\'', '').split(',')) for x in lst])

输出

[('Theres no going back', ' pop'), ('Mark my words', ' pop'), ('This love will make you levitate', ' pop'), ('Like a bird', ' like a bird without a cage', ' pop')]