tags:

views:

39

answers:

2

I have

def findfreq(nltktext, atitem)
    fdistscan = FreqDist(nltktext)
    distlist = fdistscan.keys()
    return distlist[:atitem]

which relies on FreqDist from the NLTK package, and does not work. The problem seems to be the part of the function where I try to return only the first n items of the list, using the variable atitem. So I generalize this function like so

def giveup(listname, lowerbound, upperbound)
    return listname[lowerbound:upperbound]

returning the usual error

>>> import bookroutines
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "bookroutines.py", line 70
    def giveup(listname, lowerbound, upperbound)
                                               ^
SyntaxError: invalid syntax

but hopefully also an answer from some kind person whose Python is much more fluent than mine.

+2  A: 

You need a colon (:) at the end of the def line.

def findfreq(nltktext, atitem):
    fdistscan = FreqDist(nltktext)
    distlist = fdistscan.keys()
    return distlist[:atitem]

Python's function declaration syntax is:

def FuncName(Args):
    # code
Amber
How silly of me. Thanks.
old Ixfoxleigh
A: 

operator.itemgetter() will return a function that slices a sequence if you pass it a slice object.

Ignacio Vazquez-Abrams
Er, how does this help the OP? `.keys()` returns a list, which regular slice syntax works fine on.
Amber