我一直在编写程序,从.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
我得到了以下结果:
[['But', 'breaks', 'light', 'soft', 'through', 'what', 'window', 'yonder']] [['But', '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', 'envious', 'fair', 'kill', 'moon', 'sun', 'the']] [['But', 'breaks', 'light', 'soft', 'through', 'what', 'window', 'yonder'], ['It', 'Juliet', 'and', 'east', 'is', 'is', 'sun', 'the', 'the'], ['Arise', 'and', 'envious', 'fair', 'kill', 'moon', 'sun', 'the'], ['Who', 'already', 'and', 'grief', 'is', 'pale', 'sick', 'with']]
我能做些什么来获得以下信息:
['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']
这些句子是: 但透过那边窗户的柔和光线 它是东方,朱丽叶是太阳 升起美丽的太阳,杀死嫉妒的月亮 他已经病得面色苍白
要使用一个将唯一列出元素的集合:
这会给你想要的。您可以对字符串、列表等使用
set
。sets in python 3.5最简单的方法是使用集合,并附加每个单词。在
您使用
line.split()
正确地将每一行拆分为一个单词列表,但是您没有遍历刚刚创建的名为words
的新列表。而是将列表words
作为对象与lst
的内容进行比较,然后将words
作为对象附加到lst
。这使得lst
成为一个列表列表,如您在收到的结果中所示。在为了获得您要查找的单词数组,您必须遍历
words
并单独添加每个单词,只要它不在lst
中:编辑:找到了关于相同问题的another question/answer可能是同一个类赋值。在
相关问题 更多 >
编程相关推荐