首页 > 解决方案 > 如何将文本文件转换为一个列表

问题描述

我有一个包含几行的文本文件:

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)"]

我究竟做错了什么?

标签: python

解决方案


您可以为此使用stripandreadlines方法:

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)']

推荐阅读