将txt文档转成列表转为[[开头的列表,而不是['[

Convert a txt document to a list to a list starting with [[, instead of ['[

我有一个包含这种类型文本的 .txt 文档:

[(“Vazhdo”,”verb”),(“të”,”粒子”),(“ecësh”,”verb”),(“!”,”excl.”)]

(代表一个句子和每个词的词性标签)

我想要 python 中的列表列表,如下所示:

[[(“Vazhdo”,”verb”),(“të”,”粒子”),(“ecësh”,”verb”),(“!”,”excl.”)]]

但是我得到了这个:

['[(“Vazhdo”,”verb”),(“të”,”particle”),(“ecësh”,”verb”),(“!”,”excl.”)]\ n']

我使用的代码是:

import io
f=io.open("test.txt", mode="r", encoding="utf-8-sig")
f_list = list(f)

如何避免 ['[ .... ]\n'] ?

谢谢!

看起来你可以做到

import json
data = json.load(open('test.txt'))

这个答案 错误 抱歉... [("word","QQ")] 有效 json 作为 json 不支持元组

相反,您应该可以做到

import ast
data = ast.literal_eval(io.open("test.txt", mode="r", encoding="utf-8-sig").read())

这是我的版本

import io,ast,requests

#text file available at
text_url = "https://gist.githubusercontent.com/joranbeasley/a50d940d9ac47e8458f027d3cc88e236/raw/3a65169d30e653e085284de16b1ee715f3596c95/example.txt"
with open("example.txt","wb") as f:
    # download and save textfile
    f.write(requests.get(text_url).content)

data = ast.literal_eval(io.open('example.txt',encoding='utf8').read())
print(data)
print(data[0])
print(data[0][0])

结果

[('Vazhdo', 'verb'), ('të', 'particle'), ('ecësh', 'verb'), ('!', 'excl.')]
('Vazhdo', 'verb')
Vazhdo

可以用strip方法删除空行,如:

f_list[0] = f_list[0].rstrip()

io.open() 将文件读取为字符串列表,因此您需要 evaluate .txt 文件的每一行以获取列表列表而不是列表字符串。

您可以通过以下方式实现:

temp = ['[("Vazhdo","verb"),("të","particle"),("ecësh","verb"),("!","excl.")]\n']
f_list = []
for i in temp:
  f_list.append(eval(i.strip()))

print(f_list)

#[[('Vazhdo', 'verb'), ('të', 'particle'), ('ecësh', 'verb'), ('!', 'excl.')]]


#OR

f_list = [eval(lst.strip()) for lst in f_list]