【问题标题】:I am trying to read, append and sort all words in a file using Python in TextWrangler application.我正在尝试在 TextWrangler 应用程序中使用 Python 读取、附加和排序文件中的所有单词。
【发布时间】:2016-06-30 08:58:06
【问题描述】:

问题: 打开文件 romeo.txt 并逐行读取。对于每一行,使用 split() 方法将该行拆分为一个单词列表。该程序应该建立一个单词列表。对于每行上的每个单词,检查该单词是否已经在列表中,如果没有,则将其附加到列表中。程序完成后,按字母顺序对生成的单词进行排序和打印。

fname = raw_input('Enter the file name: ')
file = open(fname)
romeo = list()
for line in file:   
    words = line.split()    
    for current_word in words : 
        if current_word in romeo:   
            continue
        romeo.append(current_word)
print romeo.sort()

我得到“无”的输出。我不确定我做错了什么 This link is where the romeo.txt file is found.

【问题讨论】:

    标签: python list file split append


    【解决方案1】:

    您得到None 的原因是因为romeo.sort() 进行了适当的排序,所以它实际上什么也不返回。在调用romeo.sort() 之后,您实际上只需要打印romeo。

    所以,不要打印romeo.sort(),而是打印:

    print(romeo)
    

    【讨论】:

      【解决方案2】:

      如果没有继续:

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

      【讨论】:

        【解决方案3】:

        fname = input("请输入文件名:")

        fh = open(fname)

        lst = list()

        fh 中的行:

        x=line.split()
        
        for word in x:
        
        if word not in lst:
            lst.append(word)
            lst.sort()
        

        打印(lst)

        【讨论】:

        • 感谢您的回答,但到目前为止它仅包含代码。添加一些文字来解释您的答案将对提问者和其他人有所帮助。
        • 你的代码缩进不正确,所以代码行不通。请edit您的答案并修复缩进,然后将代码标记为代码块,以便正确显示(最简单的方法是突出显示代码并按 control+K 或 command+K)。格式指南为here
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-08-23
        • 1970-01-01
        • 2021-11-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多