为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

陪伴而非守候 2021-12-17 15:53:51
我正在尝试将 .txt 文件转换为常规 Python 列表。我之前也做过这个,但是之前的情况涉及到手动构建的文件。我目前正在尝试处理由另一个 Python 脚本组成的 .txt 文件,该脚本将列表写入所述 .txt 文件。我不确定为什么 Python 认为这些格式不同这就是我的意思:第一个 .txt 看起来像:(我们称之为x.txt)I like dogsGo 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']
查看完整描述

3 回答

?
LEATH

TA贡献1936条经验 获得超7个赞

如果您的'y.txt'文件包含['I like dogs', 'Go home', 'This is the greatest Ice Cream ever']没有字符串格式的内容,并且在阅读文本行后您希望将列表分配给某个变量,请尝试以下操作:


from ast import literal_eval

with 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_eval

with open('y.txt', 'r', encoding = 'utf-8') as f:

    b = f.readlines()

    l = [literal_eval(k.strip()) for k in b]


查看完整回答
反对 回复 2021-12-17
?
米脂

TA贡献1836条经验 获得超3个赞

列表可以直接从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']


查看完整回答
反对 回复 2021-12-17
?
慕村225694

TA贡献1880条经验 获得超4个赞

如果只有一行包含您的列表作为字符串并且它是第一行,我建议您试试这个


fil = open('y.txt', 'r', encoding="utf-8")

lis = eval(fil.readlines()[0])

现在你应该可以使用 list - lis


让我知道这是否有效。


查看完整回答
反对 回复 2021-12-17
  • 3 回答
  • 0 关注
  • 246 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号