繁体   English   中英

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

[英]Convert 4 sentences from text file and append all the words into a new list without repeating the words

我一直在研究从 .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', '软','通过','什么','窗口','那边'],['它','朱丽叶','和','东','是','是','太阳',' ', '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', '羡慕' , 'fair', 'kill', 'moon', 'sun', 'the'], ['Who', 'already', 'and', 'grief', 'is', 'pale', 'sick' , '与']]]

我能做些什么来获得以下内容:

['出现','但是','它','朱丽叶','谁','已经','和','休息','东方','羡慕','公平','悲伤','是', 'kill', 'light', 'moon', '苍白', 'sick', 'soft', 'sun', 'the', 'through', 'what', 'window', 'with' , '那边']

句子是:但是柔和的光线透过那扇窗户打破它是东方,朱丽叶是太阳升起美丽的太阳,杀死嫉妒的月亮谁已经病了,悲伤而苍白

您想使用一个可以唯一列出元素的集合:

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(' '))

这会给你你想要的。 您可以在 python 3.5 中的字符串、列表等集合上使用set

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

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)

编辑:找到关于同一问题的另一个问题/答案- 可能是同一个班级作业。

集合可用于删除重复项, split方法将拆分任何类型的空白 - 包括行尾。 所以这个任务可以简化为一个非常简单的单行:

lst = sorted(set(open(fname).read().split()))

我正在做同样的任务。 我使用的代码如下:

fname = input("Enter file name: ")
fh = open(fname)
lst = list()
for line in fh:
    line = line.rstrip()
    words = line.split()
    for word in words:
        if word not in lst:
            lst.append(word)
lst.sort()
print(lst)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM