Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invalid syntax on importing nltk in python 2.7

when I executed the below code in python 2.7 CLI

import nltk

it is showing the following error

SyntaxError:Invalid Syntax

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/nani/.local/lib/python2.7/site-packages/nltk/__init__.py", line 128, in <module>
from nltk.collocations import *
File "/home/nani/.local/lib/python2.7/site-packages/nltk/collocations.py", line 35, in <module>
from nltk.probability import FreqDist
File "/home/nani/.local/lib/python2.7/site-packages/nltk/probability.py", line 333
print("%*s" % (width, samples[i]), end=" ")                                      ^
SyntaxError: invalid syntax

How to fix this?

like image 340
MathGeek Avatar asked May 02 '20 14:05

MathGeek


People also ask

Why pip install invalid syntax?

The python pip invalid syntax error is occurring because pip is run from the command line, not the Python interpreter. It is a program that installs modules, so you can use them from Python. Once you have installed the module, then you can open the Python shell and do import selenium.

What is import NLTK in Python?

NLTK is a toolkit build for working with NLP in Python. It provides us various text processing libraries with a lot of test datasets. A variety of tasks can be performed using NLTK such as tokenizing, parse tree visualization, etc…

Why is it saying += is invalid syntax Python?

x += 1 is an augmented assignment statement in Python. You cannot use statements inside the print statement , that is why you get the syntax error. You can only use Expressions there.


2 Answers

nltk dropped support to Python2, Try to use older versions of nltk in which it supports python 2 and I found out that nltk 3.0 version supports python 2 [edited - Thanks to user2357112 supports Monica ]

So, Try to download and install previous versions of nltk with the command

pip install nltk==3.0

You can change the version number which is 3.0 in the above mentioned case and can install suitable version whichever you feels working.

It worked for me.If anyone facing same problem can try above mentioned method.

like image 97
MathGeek Avatar answered Oct 19 '22 16:10

MathGeek


The code is using the print function, which in Python 2.7 has to be enabled with

from __future__ import print_function

However, this has to appear in the module being imported, not the code importing the module. nltk appears to assume it will be imported by a Python 3 interpreter.

like image 23
chepner Avatar answered Oct 19 '22 18:10

chepner