简体   繁体   中英

how to sort this python code alphabetically

i've tried so hard to sort these code alphabetically but still not working. tis is the error message :

Traceback (most recent call last): File "D:\\Eclipse Workspace\\tugas1\\src\\h.py", line 15, in for word in set(l): TypeError: 'NoneType' object is not iterable

here the code :

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()

The problem is the .sort() . It sorts the list in place and returns None , so that is the result of the assignment. l is always None. . Do the sort separately, after all the other stuff.

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

Just BTW, there is no need to compile a regex if you're just going to use it once. No harm in doing so, though.

.sort() sorts the list in place. It does not return the sorted list. Because it doesn't, it default to return None .

Thus, l = None . You don't want this.

Your code should be:

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

...

Sparse is better than dense . Don't try to put everything in one line

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM