python - 将 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\',]]
我以为双括号只存在于熊猫中?我在哪里错了?如何获得常规列表格式输出。
注意:为了提供一些上下文,我试图将此列表提供给一些文本清理脚本。当我尝试将第二个输出输入其中时,我没有收到错误,但它会将字符串列表转换为列表中的一个长字符串,例如:['IlikedogsGohomeThisisthegreatestIceCreamever']
解决方案
如果您的'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]
推荐阅读
- javascript - 重置无线电选择
- c++ - 带有模板成员的 C++ 类,它使用任意模板参数构造模板成员
- android - android - 屏幕截图显示黑色区域
- vb.net - 通过 httpwebrequest vb.net 检查 Instagram 用户
- sql - 选择上一年到当前日期
- arrays - Nodejs - FindOneAndUpdate 方法有效,但使我的网站在 events.js 上崩溃(使用 mongo)
- python - Python:更快的标准化
- node.js - 画布背景无意中浮现
- java - 如何使用 LocalSocket 修复“MediaRecorder.start()”上的“java.lang.IllegalStateException”
- css - 将 CSS 文件从 React index.html 链接到 Flask 后端