【发布时间】:2016-07-11 22:44:55
【问题描述】:
我正在尝试将以下文本中的唯一单词提取到 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']]
谢谢!!
【问题讨论】:
-
for word in line: word =line.lower().split()。这里没有word in line的用处,因为您在它的正下方重新分配了word。相反:for word in line.split(): lst.append(word)可能更接近你想要的。 -
感谢大家的帮助,这些都非常有帮助。而且比我想出的解决方案干净得多:使用
count = count + 1循环和word[count]。