我正在尝试将以下文本中的独特单词提取到 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/