我想從下面的文本中提取出獨特的單詞到1列表中。蟒蛇從多行提取單詞到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 line in line:word = line.lower()。split()'。這裏沒有用'你正在重新分配「word」。相反:'line.split()中的單詞:lst.append(word)'可能更接近你想要的。 – Evert
感謝您的幫助,這些都非常有幫助。並且比我想出的解決方案更清潔:使用'count = count + 1'循環和'word [count]'。 – Nodar95