猿问

将 Python 导出列表 .txt 转换为常规 Python 列表

我正在尝试将 .txt 文件转换为常规 Python 列表。我之前也做过这个,但是之前的情况涉及到手动构建的文件。我目前正在尝试处理由另一个 Python 脚本组成的 .txt 文件,该脚本将列表写入所述 .txt 文件。我不确定为什么 Python 认为这些格式不同


这就是我的意思:


第一个 .txt 看起来像:


(我们称之为x.txt)


I like dogs

Go home 

This is the greatest Ice Cream ever

现在,如果我这样做:


f = open('x.txt', encoding = "utf8")


z = f.readlines()


print(z)

我得到


['I like dogs','Go home','This is the greatest Ice Cream ever']

这正是我想要的^


我当前的 .txt 文件如下所示:


(我们称之为 y.txt)


['I like dogs','Go home','This is the greatest Ice Cream ever']

现在,如果我这样做:


f = open('y.txt', encoding = "utf8")


z = f.readlines()


print(z)

我得到一个奇怪的输出,看起来像:


['[\'I like dogs. \', \'Go home\', \'This is the greatest Ice Cream 

ever\',]]

我以为双括号只存在于 Pandas 中?我哪里出错了?如何获得常规列表格式输出。


注意:为了提供一些上下文,我试图将此列表输入到一些文本清理脚本中。当我尝试将第二个输出输入其中时,我没有收到错误消息,但它将字符串列表转换为列表中的一个长字符串,例如:['IlikedogsGohomeThisisthegreatestIceCreamever']


陪伴而非守候
浏览 247回答 3
3回答

LEATH

如果您的'y.txt'文件包含['I like dogs', 'Go home', 'This is the greatest Ice Cream ever']没有字符串格式的内容,并且在阅读文本行后您希望将列表分配给某个变量,请尝试以下操作:from ast import literal_evalwith open('y.txt', 'r', encoding = 'utf-8') as f:    b = f.readlines()    print(b)    # OUTPUT - ["['I like dogs','Go home','This is the greatest Ice Cream ever']"]    l = literal_eval(b[0])    print(l)    # OUTPUT - ['I like dogs', 'Go home', 'This is the greatest Ice Cream ever']使用上述代码有一个限制——只有当文本文件包含单个列表时,这才有效。如果里面包含多个列表'y.txt',试试这个:from ast import literal_evalwith open('y.txt', 'r', encoding = 'utf-8') as f:    b = f.readlines()    l = [literal_eval(k.strip()) for k in b]

米脂

列表可以直接从y.txtas中提取>>> with open('y.txt', 'r') as file:...     line = file.readlines()[0].split("'")[1::2]... >>> line['I like dogs', 'Go home', 'This is the greatest Ice Cream ever']

慕村225694

如果只有一行包含您的列表作为字符串并且它是第一行,我建议您试试这个fil = open('y.txt', 'r', encoding="utf-8")lis = eval(fil.readlines()[0])现在你应该可以使用 list - lis让我知道这是否有效。
随时随地看视频慕课网APP

相关分类

Python
我要回答