【发布时间】:2016-11-04 17:28:50
【问题描述】:
我一直在研究从 .txt 文件中读取 4 个句子并将所有单词附加到一个新的空列表中的程序。
我的代码如下:
fname = raw_input("Enter file name: ")
fh = open(fname)
lst = list()
for line in fh:
line = line.rstrip()
words = line.split()
words.sort()
if words not in lst:
lst.append(words)
print lst
我得到了以下结果:
[['但是', 'breaks', 'light', 'soft', 'through', 'what', 'window', '那边']] [['但是', 'breaks', 'light', 'soft', 'through', 'what', 'window', 'yonder'], ['It', 'Juliet', 'and', 'east', 'is', 'is', 'sun', 'the', 'the']] [['but', 'breaks', 'light', 'soft', 'through', 'what', 'window', 'yonder'], ['It', 'Juliet', 'and', 'east', 'is', 'is', 'sun', 'the', 'the'], ['Arise', 'and', '羡慕', 'fair', 'kill', 'moon', 'sun', 'the']] [['But', 'breaks', 'light', 'soft', '通过','什么','窗口','那边'],['它','朱丽叶','和', 'east', 'is', 'is', 'sun', 'the', 'the'], ['Arise', 'and', 'envious', 'fair', 'kill', 'moon', 'sun', 'the'], ['Who', 'already', 'and', '悲伤','是','苍白','生病','与']]
我可以做些什么来获得以下内容:
['Arise', 'But', 'It', 'Juliet', 'Who', 'already', 'and', 'breaks', '东方','羡慕','公平','悲伤','是','杀','光','月亮', '苍白','生病','柔软','阳光','the','透','什么','窗口', '与','那边']
句子是: 但是柔和的光线从那边的窗户打破 它是东方,朱丽叶是太阳 升起美丽的太阳,杀死嫉妒的月亮 谁已经病入膏肓,悲痛欲绝
【问题讨论】:
-
你能把那4句话的内容显示出来吗?
-
你能用文字解释一下输出的问题吗?这可能会帮助您了解算法出了什么问题。
-
看看list.append和list.extend的区别。此外,如果您正在寻找独特的东西,那么您需要设置对象。
标签: python