我正在尝试在 TextWrangler 应用程序中使用 Python 读取、附加和排序文件中的所有单词。

I am trying to read, append and sort all words in a file using Python in TextWrangler application.

问题: 打开文件 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()

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

你得到 None 的原因是因为 romeo.sort() 进行了适当的排序,所以它实际上 returns 什么都没有。在调用 romeo.sort().

之后,您实际上只需要打印 romeo

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

print(romeo)

没有继续:

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)

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

fh = 打开(fname)

lst = 列表()

fh 中的行:

x=line.split()

for word in x:

if word not in lst:
    lst.append(word)
    lst.sort()

打印(lst)