【发布时间】:2016-08-09 00:11:32
【问题描述】:
我正在编写一个程序,将文件中的文本读取到列表中,然后使用 split 函数将其拆分为单词列表。对于每个单词,我需要检查它是否已经在列表中,如果没有,我需要使用 append 函数将它添加到列表中。
想要的输出是:
['Arise', 'But', 'It', 'Juliet', 'Who', 'already', 'and', 'breaks', 'east', 'envious', 'fair', 'grief', 'is', 'kill', 'light', 'moon', 'pale', 'sick', 'soft', 'sun', 'the', 'through', 'what', 'window', 'with', 'yonder']
我的输出是:
[['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']]
我一直在尝试对其进行排序并删除开头和结尾的双方括号“[[ & ]]”,但我无法这样做。出于某种原因,sort() 函数似乎不起作用。
请让我知道我在哪里犯了错误。
word_list = []
word_list = [open('romeo.txt').read().split()]
for item in word_list:
if item in word_list:
continue
else:
word_list.append(item)
word_list.sort()
print word_list
【问题讨论】:
-
正如 TerryA 所说,您需要使用 2 个单独的列表,但是您的代码对输入列表和输出列表都使用了
word_list,并且您正在使用 @ 的列表中创建一个列表987654325@。最有效的方法是使用set,但我猜你正在做家庭作业,你必须使用列表来完成。您还应该了解如何使用with打开文件。 -
语句 "open('remeo.txt).read().split()" 已经返回一个列表,所以从 "[`open('remeo.txt).read 中删除 [ ] ().split() ]"
标签: python list python-2.7