【问题标题】:Python append words to a list from filePython将单词附加到文件中的列表
【发布时间】: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


【解决方案1】:

去掉括号

word_list = open('romeo.txt').read().split()

【讨论】:

    【解决方案2】:

    使用两个单独的变量。此外,str.split() 返回一个列表,因此无需在其周围放置 []:

    word_list = []
    word_list2 = open('romeo.txt').read().split()
    for item in word_list2:
        if item in word_list:
            continue
        else:
            word_list.append(item)
    word_list.sort()
    print word_list
    

    此时您正在检查if item in word_list:,这将始终正确,因为item 来自word_list。让 item 从另一个列表中迭代。

    【讨论】:

    • 感谢您的帮助!我是 Python 新手,这对我很有帮助。
    【解决方案3】:

    如果顺序无关紧要,那就是单排

    uniq_words = set(open('romeo.txt').read().split())
    

    如果顺序很重要,那么

    uniq_words = []
    for word in open('romeo.txt').read().split():
        if word not in uniq_words:
           uniq_words.append(word) 
    

    如果要排序,则采用第一种方法,使用sorted()。

    【讨论】:

      【解决方案4】:

      语句open('remeo.txt).read().split() 已返回一个列表,因此请从[open('remeo.txt).read().split() ] 中删除 [ ]

      如果我说

      word = "Hello\nPeter"
      s_word = [word.split()] # print [['Hello', wPeter']]
      But
      s_word = word.split() # print ['Hello', wPeter']
      

      【讨论】:

        【解决方案5】:

        Split 返回一个列表,因此无需在open...split 周围加上方括号。要删除重复项,请使用集合:

        word_list = sorted(set(open('romeo.txt').read().split()))
        print word_list
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-03-16
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多