首页 > 解决方案 > 将不同行中的单词拆分为Python中的列表

问题描述

我有一个文本文件,其文本为:

Hello All,

Hope you are enjoying learning Python
We have tried to cover every point in detail to avoid confusion
Happy Reading

我想将每个单词按以下格式分隔到一个列表中,['Hello','All,','Hope','you','are','enjoying','learning','Python','We ','有','试过','to','cover','every','point','in','detail','to','avoid','confusion','Happy', '阅读。我已经尝试了下面的代码,它正在工作,但唯一的问题是输出进入双方括号并在一个新行中,如下所示

words = [open('example.txt').read().split()]
words

[['你好','所有,','希望','你','是','享受','学习','Python','我们','有','尝试','to' , 'cover', 'every', 'point', 'in', 'detail', 'to', 'avoid', 'confusion', 'Happy', 'Reading']] 我是 python 和学习新手。如果有人可以帮助我,那将有很大帮助。我希望输出在单个方括号中并继续。

标签: listfile-handling

解决方案


words = open('example.txt').read().split()
print(words)

只需卸下支架。

或者如果你必须使用旧代码,你可以使用 words[0]。


推荐阅读