我正在尝试编写一个python代码,它从文本文件中读取一堆行,然后将这些行拆分为单词。然后对于每个单词,它检查该单词是否已经存在于列表中,如果不存在则添加到该单词并最终对列表进行排序并打印最终列表。这就是我到目前为止所写的内容。
fname = raw_input("Enter file name: ")
fh = open(fname)
new = list()
for line in fh:
line = line.rstrip()
word = line.split()
for w in word:
if w not in new:
final = new.append(w)
result = final.sort()
print result
但我收到以下错误..
AttributeError: 'NoneType' object has no attribute 'sort' on line 12
不知道为什么?有什么帮助吗?
由于 众议员
答案 0 :(得分:1)
fname = raw_input("Enter file name: ")
with open(fname) as fh: # use with to automatically close the file
final = []
new = [x.rstrip().split() for x in fh] # strip and split into sublists of words
for ele in new:
for word in ele: # for every word in each sublist
if not word in final: # if word not already in final then add word
final.append(word)
final.sort() # sort
print final
答案 1 :(得分:0)
append()
和sort()
都是就地的,不会返回任何内容。
你可以改写
final = new.append(w)
result = final.sort()
像这样:
final = new + [w]
result = sorted(final)
请注意,排序可以(并且应该)从循环中移出:它非常昂贵,并且不需要为每个单词完成。
最后,我建议使用集而不是列表。它们可以自动确保唯一性,从而使代码更简单,并且通常更适合这种用例。
答案 2 :(得分:0)
文件中所有单词的排序列表:
fname = raw_input("Enter file name: ")
with open(fname) as fh:
result = sorted(set(fh.read().split()))
答案 3 :(得分:0)
错误在于.append()方法只是附加到现有列表而不返回任何内容。因此,您应该将代码重写为:
fname = raw_input("Enter file name: ")
fh = open(fname)
new = list()
for line in fh:
line = line.rstrip()
word = line.split()
for w in word:
if w not in new:
new.append(w)
new.sort() #rather than sorting it in each iteration, why not just sort it at the end?
print new