python - 如何将文本文件转换为一个列表
问题描述
我有一个包含几行的文本文件:
someone can tell/figure
a/the squeaky wheel gets the grease/oil
accounts for (someone or something)
我将其作为一个列表,但它为每一行返回一个列表
with open('words.txt') as f:
text = [line.split('\n') for line in f]
print(text)
Output:
[['someone can tell/figure', ''], ['a/the squeaky wheel gets the grease/oil', ''], ['accounts for (someone or something)', '']]
我想要这样的东西
['someone can tell/figure', 'a/the squeaky wheel gets the grease/oil', "accounts for (someone's or something)"]
我究竟做错了什么?
解决方案
您可以为此使用strip
andreadlines
方法:
someone can tell/figure
a/the squeaky wheel gets the grease/oil
accounts for (someone or something)
(确保正确打开文件)
with open('words.txt', "r") as f:
text = [line.strip() for line in f] #or rstrip()
print(text)
输出:
['someone can tell/figure', 'a/the squeaky wheel gets the grease/oil', 'accounts for (someone or something)']
推荐阅读
- javascript - 使用 axios 链接异步调用的理想方式
- javascript - 基于函数顺序的不同函数输出
- sql - 如何根据另一列中的值找到一列中的最大值?SQL
- f# - 删除 F# 中的嵌套匹配?
- bash - bash 鲁棒性:为了“退出”清理例程的目的,什么是正确且可移植的陷阱方法?
- docker - Elixir 在 docker 中请求缓慢,凤凰代码重新加载器开启
- javascript - 如果用户更改输入而不保存,则启动确认对话框
- android - Android - 将 MP3 从立体声编码为单声道
- google-cloud-run - 云运行中的路由:相当于dispatch.yaml / 云运行的替换服务
- react-native - 推送器上的触发事件(React Native)