从文本文件中转换4个句子,将所有单词添加到一个新列表中,而不重复单词

2024-05-15 16:20:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在编写程序,从.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']

这些句子是: 但透过那边窗户的柔和光线 它是东方,朱丽叶是太阳 升起美丽的太阳,杀死嫉妒的月亮 他已经病得面色苍白


Tags: andtheislinewindowwhatbutlight
3条回答

要使用一个将唯一列出元素的集合:

my_string = "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"    
lst = set(my_string.split(' '))

这会给你想要的。您可以对字符串、列表等使用setsets in python 3.5

最简单的方法是使用集合,并附加每个单词。在

file_name = raw_input("Enter file name: ")
with open(file_name, 'r') as fh: 
    all_words = set()
    for line in fh:
        line = line.rstrip()
        words = line.split()
        for word in words:     
            all_words.add(word)
print(all_words)

您使用line.split()正确地将每一行拆分为一个单词列表,但是您没有遍历刚刚创建的名为words的新列表。而是将列表words作为对象与lst的内容进行比较,然后将words作为对象附加到lst。这使得lst成为一个列表列表,如您在收到的结果中所示。在

为了获得您要查找的单词数组,您必须遍历words并单独添加每个单词,只要它不在lst中:

for word in words:
    if word not in lst:
      lst.append(word)

编辑:找到了关于相同问题的another question/answer可能是同一个类赋值。在

相关问题 更多 >