I'm have this function:
def ngrams(word):
for i in range(1, len(word) + 1):
yield word[:i]
..and I got an error
2012-03-09 19:37:31,928 ERROR worker-bootstrap: Error running worker process
net.grinder.scriptengine.jython.JythonScriptExecutionException: SyntaxError: ('invalid syntax', ('C:\\grinder-3.7.1\\lib
\\.\\nb-romg-file-store\\current\\grinder_test.py', 72, 15, ' yield word[:i] '))
(no code object) at line 0
Is there any way to make yield
work? I tried the same function in jython
console - if works normally.
In older versions of Jython, generators (functions using the yield
keyword) are not available by default. You can try enabling the feature by adding
from __future__ import generators
to the top of your source file. If this doesn't work, you're probably out of luck and generators simply are not available in that version of Jython. In that case, you can try to simulate the behaviour using lists:
def ngrams(word):
result = []
for i in range(1, len(word) + 1):
result.append(word[:i])
return result
This is dead ugly, but it should work even in the most ancient Python implementations.