I've got this issue where this piece of code:
import nltk
sentence = "Hello everyone on stackoverflow!"
tokens = nltk.word_tokenize(sentence)
print tokens
Throws me this kind of error, when ran from within PowerShell:
Traceback (most recent call last):
File "tokenize.py", line 1, in <module>
import nltk
File "C:\PYTHON27\lib\site-packages\nltk\__init__.py", line 105, in <module>
from collocations import *
File "C:\PYTHON27\lib\site-packages\nltk\collocations.py", line 37, in <module>
from nltk.util import ingrams
File "C:\PYTHON27\lib\site-packages\nltk\util.py", line 12, in <module>
import pydoc
File "C:\PYTHON27\LIB\pydoc.py", line 55, in <module>
import sys, imp, os, re, types, inspect, __builtin__, pkgutil, warnings
File "C:\PYTHON27\LIB\inspect.py", line 39, in <module>
import tokenize
File "C:\stuff\tokenize.py", line 4, in <module>
tokens = nltk.word_tokenize(sentence)
AttributeError: 'module' object has no attribute 'word_tokenize'
But the same code has no issues in IDLE:
>>> import nltk
>>> sentence = "Hello everyone on stackoverflow!"
>>> tokens = nltk.word_tokenize(sentence)
>>> print tokens
['Hello', 'everyone', 'on', 'stackoverflow', '!']
>>>
I can't seem to get it fixed no matter what I do. At first, I thought it's the " " space in the directory so I changed it to "stuff", reinstalled nltk but the problem still persisted.
I'd appreciate some help :)
If I correctly read you stack trace, you called your script tokenize.py. But tokenize is allready a module of the Standard Python Library. And still accordingly to the stack trace, the tokenize module is called indirectly from nltk. But as you have a tokenize.py in your current directory Python takes it instead of the standard one.
You should rename your script to a name that does not conflict with the Standard Python Library.
Related
I am trying to convert text to speech in Python 3.10.2 using the code:
import win32com.client
speaker = win32com.client.Dispatch("SAPI.SpVoice")
speaker.Speak("Hello, it works!")
But there is continuously occuring an error:
Traceback (most recent call last): File "d:\Program\Python programing\tempCodeRunnerFile.py", line 1, in <module>
import win32com.client File "C:\Users\ASUS\AppData\Roaming\Python\Python310\site-packages\win32com\client\__init__.py",
line 10, in <module>
from . import dynamic File "C:\Users\ASUS\AppData\Roaming\Python\Python310\site-packages\win32com\client\dynamic.py",
line 24, in <module>
from . import build File "C:\Users\ASUS\AppData\Roaming\Python\Python310\site-packages\win32com\client\build.py",
line 638, in <module>
valid_identifier_chars = string.ascii_letters + string.digits + "_" AttributeError: module 'string' has no attribute 'ascii_letters'
you wrote two lines of code in the same line
Try this
import win32com.client
speaker = win32com.client.Dispatch("SAPI.SpVoice")
speaker.Speak("Hello, it works!")
or try to put a semicolon after the first line of code
Try this
import win32com.client; speaker =win32com.client.Dispatch("SAPI.SpVoice")
speaker.Speak("Hello, it works!")
either way should work
Screenshot of the error
After installing nltk using pip3 install nltk
I am unable to import nltk in python shell in macOS
File "<stdin>", line 1, in <module>
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/nltk/__init__.py", line 137, in <module>
from nltk.text import *
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/nltk/text.py", line 29, in <module>
from nltk.tokenize import sent_tokenize
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/nltk/tokenize/__init__.py", line 65, in <module>
from nltk.tokenize.casual import TweetTokenizer, casual_tokenize
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/nltk/tokenize/casual.py", line 49, in <module>
import regex # https://github.com/nltk/nltk/issues/2409
File "/Users/userId/Library/Python/3.9/lib/python/site-packages/regex/__init__.py", line 1, in <module>
from .regex import *
File "/Users/userId/Library/Python/3.9/lib/python/site-packages/regex/regex.py", line 419, in <module>
import regex._regex_core as _regex_core
File "/Users/userId/Library/Python/3.9/lib/python/site-packages/regex/_regex_core.py", line 21, in <module>
import regex._regex as _regex
ImportError: dlopen(/Users/userId/Library/Python/3.9/lib/python/site-packages/regex/_regex.cpython-39-darwin.so, 2): no suitable image found. Did find:
/Users/userId/Library/Python/3.9/lib/python/site-packages/regex/_regex.cpython-39-darwin.so: code signature in (/Users/userId/Library/Python/3.9/lib/python/site-packages/regex/_regex.cpython-39-darwin.so) not valid for use in process using Library Validation: Trying to load an unsigned library```
Just ran into this, I found that the following fixes it:
xcrun codesign --sign - "[YOUR_PATH_TO_DYLIB_HERE]"
In my case the error was like so:
ImportError: dlopen(/Users/USER/dev/cr-likes/venv/lib/python3.9/site-packages/regex/_regex.cpython-39-darwin.so, 2): no suitable image found. Did find:
/Users/USER/dev/cr-likes/venv/lib/python3.9/site-packages/regex/_regex.cpython-39-darwin.so: code signature in (/Users/USER/dev/cr-likes/venv/lib/python3.9/site-packages/regex/_regex.cpython-39-darwin.so) not valid for use in process using Library Validation: Trying to load an unsigned library
By running xcrun on the shared object, in this case /Users/USER/dev/cr-likes/venv/lib/python3.9/site-packages/regex/_regex.cpython-39-darwin.so the error is now gone.
I have this sample program from python-docx library example-extracttext.py to extract text from a docx file.
#!/usr/bin/env python
"""
This file opens a docx (Office 2007) file and dumps the text.
If you need to extract text from documents, use this file as a basis for your
work.
Part of Python's docx module - http://github.com/mikemaccana/python-docx
See LICENSE for licensing information.
"""
import sys
from docx import opendocx, getdocumenttext
if __name__ == '__main__':
try:
document = opendocx(sys.argv[1])
newfile = open(sys.argv[2], 'w')
except:
print(
"Please supply an input and output file. For example:\n"
" example-extracttext.py 'My Office 2007 document.docx' 'outp"
"utfile.txt'"
)
exit()
# Fetch all the text out of the document we just created
paratextlist = getdocumenttext(document)
# Make explicit unicode version
newparatextlist = []
for paratext in paratextlist:
newparatextlist.append(paratext.encode("utf-8"))
# Print out text of document with two newlines under each paragraph
newfile.write('\n\n'.join(newparatextlist))
It runs fine but when I put another program called tokenize.py (given just below) in the same directory.
import nltk.data
tokenizer = nltk.data.load('tokenizers/punkt/english.pickle')
fo = open(sys.argv[1], "r")
data = fo.read()
print '\n-----\n'.join(tokenizer.tokenize(data))
It gives following error.
Traceback (most recent call last):
File "./example-extracttext.py", line 14, in <module>
from docx import opendocx, getdocumenttext
File "/usr/local/lib/python2.7/dist-packages/docx-0.2.1-py2.7.egg/docx.py", line 12, in <module>
from lxml import etree
File "parsertarget.pxi", line 4, in init lxml.etree (src/lxml/lxml.etree.c:178742)
File "/usr/lib/python2.7/inspect.py", line 39, in <module>
import tokenize
File "/home/sriram/NLP_TOOLS/EDITING_TOOL/NLP/sriram_work/tokenize.py", line 3, in <module>
import nltk.data
File "/usr/local/lib/python2.7/dist-packages/nltk/__init__.py", line 106, in <module>
from decorators import decorator, memoize
File "/usr/local/lib/python2.7/dist-packages/nltk/decorators.py", line 176, in <module>
#decorator
File "/usr/local/lib/python2.7/dist-packages/nltk/decorators.py", line 154, in decorator
if inspect.isclass(caller):
AttributeError: 'module' object has no attribute 'isclass'
Please tell me how to resolve this. I want to use both the programs in a single shell script.
I added the following plugin to sublime text 2 which is meant to open the ipython qt console:
import sublime, sublime_plugin
from subprocess import call
# import os
class ipythonQtCommand(sublime_plugin.TextCommand):
def run(self, edit):
call(["start","ipython", "qtconsole", "--pylab", "--ConsoleWidget.font_size=9", "--ConsoleWidget.font_family='Consolas'"],shell=True)
Initially it worked just fine, i.e. the plugin opened an ipython shell. I then added a menu item and a key binding. At some point something must have gone wrong since now I get this error when I run the plugin:
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "C:\Chris\Python27\lib\site-packages\IPython\__init__.py", line 43, in <
odule>
from .config.loader import Config
File "C:\Chris\Python27\lib\site-packages\IPython\config\__init__.py", line 1
, in <module>
from .application import *
File "C:\Chris\Python27\lib\site-packages\IPython\config\application.py", lin
31, in <module>
from IPython.config.configurable import SingletonConfigurable
File "C:\Chris\Python27\lib\site-packages\IPython\config\configurable.py", li
e 31, in <module>
from loader import Config
File "C:\Chris\Python27\lib\site-packages\IPython\config\loader.py", line 32,
in <module>
from IPython.utils.path import filefind, get_ipython_dir
File "C:\Chris\Python27\lib\site-packages\IPython\utils\path.py", line 29, in
<module>
from IPython.utils.process import system
File "C:\Chris\Python27\lib\site-packages\IPython\utils\process.py", line 25,
in <module>
from ._process_win32 import _find_cmd, system, getoutput, AvoidUNCPath, arg
split
File "C:\Chris\Python27\lib\site-packages\IPython\utils\_process_win32.py", l
ne 21, in <module>
import ctypes
File "C:\Chris\Python27\lib\ctypes\__init__.py", line 10, in <module>
from _ctypes import Union, Structure, Array
ImportError: Module use of python26.dll conflicts with this version of Python.
I tested the script by running it line by line in the st2 shell itself and it is the last line call([...]) that causes the error. I find this a little strange since the command works ok when calling it from somewhere else, e.g. ipython itself.
There seems to be a conflict with the st2 native python. In any case I managed to get os.system(...) to work when changing the working directory using os.chdir().
I have come across a strange python module import issue.
When I trying to import the boilerpipe module,
from boilerpipe.extract import Extractor
I got this exception:
Original exception was:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/dist-packages/boilerpipe-1.2.0-py2.7.egg/boilerpipe/extract/ __init__.py", line 2, in <module>
import urllib2
File "/usr/lib/python2.7/urllib2.py", line 94, in <module>
import httplib
File "/usr/lib/python2.7/httplib.py", line 1140, in <module>
import ssl
File "/usr/lib/python2.7/ssl.py", line 58, in <module>
import textwrap
File "/usr/lib/python2.7/textwrap.py", line 40, in <module>
class TextWrapper:
File "/usr/lib/python2.7/textwrap.py", line 82, in TextWrapper
whitespace_trans = string.maketrans(_whitespace, ' ' * len(_whitespace))
AttributeError: 'module' object has no attribute 'maketrans'
I've searched over internet and saying that in Python 2.6 the 'str' module has been renamed to 'string' module. So this looks like some where in code library it didn't import "string" module properly.
Yet the really strange thing is, when I run the python code from home directory and run the same piece of code (either by using python shell or using python pyfile.py), it works fine! No more import error.
So I'm bit confusing. Can anyone give me any hint?
Thanks!
Some other script in sys.path is called "string.py" and is masking the stdlib module.
Double check to make sure that you don't have a file string.py that has been imported.
To debug this, put somewhere:
import sys
raise Exception("string module: %r" %(sys.modules.get("string"), ))
That will tell you what string module was imported (or if it shows None, no string module has been imported yet).