python将多行中的单词提取到1个列表中

标签 python list split strip

我正在尝试将以下文本中的独特单词提取到 1 个列表中。

But soft what light through yonder window breaks
It is the east and Juliet is the sun
Arise fair sun and kill the envious moon
Who is already sick and pale with grief

但我一直在列表中为文本的每一行获取一个列表。我知道我有一些“\n”要删除,但不知道如何删除。

这是我的代码:

fname = input("Enter file name: ")
fh = open(fname)
lst = list()
for line in fh:
    line = line.rstrip("\n")
    for word in line:
        word = line.lower().split()
        lst.append(word)
print(lst)

我得到的输出:

[['but', 'soft', 'what', 'light', 'through', 'yonder', 'window', 'breaks'], ['it', 'is', 'the', 'east', 'and', 'juliet', 'is', 'the', 'sun'], ['arise', 'fair', 'sun', 'and', 'kill', 'the', 'envious', 'moon'], ['who', 'is', 'already', 'sick', 'and', 'pale', 'with', 'grief']]

谢谢!!

最佳答案

当您执行 line.lower.split() 时,您会得到一个单词列表。您正在将单词列表附加到您的列表中,lst。使用扩展而不是追加。 Extend 将添加 split() 函数返回的列表的每个元素。另外,第二个 for 循环 for word in line: 是不必要的。 此外,如果您想提取唯一的单词,您可能需要查看 set 数据类型。

关于python将多行中的单词提取到1个列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38317354/

相关文章:

python - 缺少数据的python中的二维卷积

java - 如何迭代非空字符串?

regex - 如何检查字符串是否包含一组条件

java - Java中的有序LinkedList逻辑,每次都会重新分配LinearNode头

python - 如何在 Python 中使用空分隔符拆分字符串

python - vim-jedi 自动完成功能不工作

python - Python中使用默认值的多列表迭代

javascript - 如何在jquery中将字符串两两分割

java - Java中如何分割特定字符串

python - 异步将对象转换为协程。加载对象字段