-1

我已经努力按字母顺序对这些代码进行排序,但仍然无法正常工作。tis 是错误信息:

Traceback(最近一次调用最后一次):文件“D:\Eclipse Workspace\tugas1\src\h.py”,第 15 行,在 set(l) 中的单词中:TypeError: 'NoneType' object is not iterable

这里的代码:

from re import compile

l=compile("(\w[\w']*)").findall(open(raw_input('Input file: '),'r').read().lower()).sort()

f=open(raw_input('Output file: '),'w')

for word in set(l):

    print>>f, word, ':', '\t', l.count(word), 'kata'

f.close()
4

2 回答 2

2

问题是.sort(). 它对列表进行就地排序并返回None,这就是赋值的结果。l总是None.。在所有其他事情之后,单独进行排序。

l=compile("(\w[\w']*)").findall(open(raw_input('Input file: '),'r').read().lower())
l.sort()

顺便说一句,如果您只想使用一次正则表达式,则无需编译它。不过,这样做并没有什么坏处。

于 2013-09-15T00:58:00.323 回答
1

.sort()对列表进行适当的排序。它不返回排序列表。因为它没有,所以它默认返回None

因此,l = None. 你不想要这个。

您的代码应该是:

from re import compile
l = compile("(\w[\w']*)")
with open(raw_input('Input file: '),'r') as myfile:
    content = myfile.read().lower()
    l = l.findall(content)
    l.sort() # Notice how we don't assign it to anything

...

稀疏优于密集。不要试图将所有内容放在一行中

于 2013-09-15T00:44:44.310 回答