如何删除换行符并将所有单词添加到列表中

How Can I Remove Newline and Add All Words To a List

我有一个包含 4 行的 txt 文件。 (像一首诗) 我想要的是将所有单词添加到一个列表中。 例如这首诗:

I am done with you,

Don't love me anymore

我想要这样:['I'、'am'、'done'、'with'、'you'、'dont'、'love'、'me'、'anymore']

但我无法删除第一个句子的行尾,它给了我 2 个分隔列表。

romeo = open(r'd:\romeo.txt')
list = []

for line in romeo:
    line = line.rstrip()
    line = line.split()
    list = list + [line]
print(list)
with open(r'd:\romeo.txt', 'r') as msg:
    data = msg.read().replace("\n"," ")

data = [x for x in data.split() if x.strip()]

你可以这样使用regular expresion

import re
poem = '' # your poem
split = re.split(r'0|\n', poem)
print(split)

正则表达式 0 用于白色 space 和 \n 以匹配新行。

输出为:

['I', 'am', 'done', 'with', 'you,', "Don't", 'love', 'me', 'anymore']

更短:

with open(r'd:\romeo.txt', 'r') as msg:
   list = " ".join(msg.split()).split(' ')

或者删除逗号:

with open(r'd:\romeo.txt', 'r') as msg:
   list = " ".join(msg.replace(',', ' ').split()).split(' ')