Python Bag of Words NameError: name 'unicode' is not defined
Home
Public
Questions
Tags
Users
Companies
Collectives
ExploreCollectives
Teams
StackOverflowforTeams
–Startcollaboratingandsharingorganizationalknowledge.
CreateafreeTeam
WhyTeams?
Teams
CreatefreeTeam
Collectives™onStackOverflow
Findcentralized,trustedcontentandcollaboratearoundthetechnologiesyouusemost.
LearnmoreaboutCollectives
Teams
Q&Aforwork
Connectandshareknowledgewithinasinglelocationthatisstructuredandeasytosearch.
LearnmoreaboutTeams
NameError:globalname'unicode'isnotdefined-inPython3
AskQuestion
Asked
8years,11monthsago
Modified
7monthsago
Viewed
292ktimes
174
IamtryingtouseaPythonpackagecalledbidi.Inamoduleinthispackage(algorithm.py)therearesomelinesthatgivemeerror,althoughitispartofthepackage.
Herearethelines:
#utf-8?weneedunicode
ifisinstance(unicode_or_str,unicode):
text=unicode_or_str
decoded=False
else:
text=unicode_or_str.decode(encoding)
decoded=True
andhereistheerrormessage:
Traceback(mostrecentcalllast):
File"",line1,in
bidi_text=get_display(reshaped_text)
File"C:\Python33\lib\site-packages\python_bidi-0.3.4-py3.3.egg\bidi\algorithm.py",line602,inget_display
ifisinstance(unicode_or_str,unicode):
NameError:globalname'unicode'isnotdefined
HowshouldIre-writethispartofthecodesoitworksinPython3?
AlsoifanyonehaveusedbidipackagewithPython3pleaseletmeknowiftheyhavefoundsimilarproblemsornot.Iappreciateyourhelp.
pythonunicodepython-3.xnameerrorbidi
Share
Improvethisquestion
Follow
editedNov9,2013at14:53
MartijnPieters♦
989k275275goldbadges38913891silverbadges32473247bronzebadges
askedNov9,2013at14:51
TJ1TJ1
6,5491919goldbadges7171silverbadges113113bronzebadges
Addacomment
|
7Answers
7
Sortedby:
Resettodefault
Highestscore(default)
Trending(recentvotescountmore)
Datemodified(newestfirst)
Datecreated(oldestfirst)
276
Python3renamedtheunicodetypetostr,theoldstrtypehasbeenreplacedbybytes.
ifisinstance(unicode_or_str,str):
text=unicode_or_str
decoded=False
else:
text=unicode_or_str.decode(encoding)
decoded=True
YoumaywanttoreadthePython3portingHOWTOformoresuchdetails.ThereisalsoLennartRegebro'sPortingtoPython3:Anin-depthguide,freeonline.
Lastbutnotleast,youcouldjusttrytousethe2to3tooltoseehowthattranslatesthecodeforyou.
Share
Improvethisanswer
Follow
editedNov9,2013at15:07
answeredNov9,2013at14:52
MartijnPieters♦MartijnPieters
989k275275goldbadges38913891silverbadges32473247bronzebadges
2
SoshouldIwrite:ifisinstance(unicode_or_str,str)?Howabout'unicode_or_str'?
– TJ1
Nov9,2013at14:56
1
Thevariablenamedoesn'tmuchmatterhere;ifisinstance(unicode_or_str,str)shouldjustwork.Renamingthevariablenameisoptional.
– MartijnPieters
♦
Nov9,2013at14:57
Addacomment
|
48
Ifyouneedtohavethescriptkeepworkingonpython2and3asIdid,thismighthelpsomeone
importsys
ifsys.version_info[0]>=3:
unicode=str
andcanthenjustdoforexample
foo=unicode.lower(foo)
Share
Improvethisanswer
Follow
answeredNov13,2018at17:36
GoblinhackGoblinhack
2,60311goldbadge2323silverbadges2626bronzebadges
1
2
Thisistherightidea,niceanswer.Justtoaddadetail,ifyouareusingthesixlibrarytomanagePython2/3compatibility,youcanmakethis:ifsix.PY3:unicode=strinsteadofsys.version_infostuff.ThisisalsoveryhelpfulforpreventinglintererrorsrelatedtounicodebeingundefinedinPython3,withoutneedingspeciallinterruleexemptions.
– ely
Sep6,2019at18:30
Addacomment
|
24
YoucanusethesixlibrarytosupportbothPython2and3:
importsix
ifisinstance(value,six.string_types):
handle_string(value)
Share
Improvethisanswer
Follow
answeredJul12,2017at20:22
atmatm
1,5932020silverbadges2121bronzebadges
0
Addacomment
|
4
Onecanreplaceunicodewithu''.__class__tohandlethemissingunicodeclassinPython3.ForbothPython2and3,youcanusetheconstruct
isinstance(unicode_or_str,u''.__class__)
or
type(unicode_or_str)==type(u'')
Dependingonyourfurtherprocessing,considerthedifferentoutcome:
Python3
>>>isinstance(u'text',u''.__class__)
True
>>>isinstance('text',u''.__class__)
True
Python2
>>>isinstance(u'text',u''.__class__)
True
>>>isinstance('text',u''.__class__)
False
Share
Improvethisanswer
Follow
editedDec22,2021at16:38
answeredNov25,2020at10:55
FriedrichFriedrich
2,13711goldbadge1212silverbadges2828bronzebadges
0
Addacomment
|
1
HopeyouareusingPython3,
Strareunicodebydefault,soplease
ReplaceUnicodefunctionwithStringStrfunction.
ifisinstance(unicode_or_str,str):##Replaceswithstr
text=unicode_or_str
decoded=False
Share
Improvethisanswer
Follow
answeredMar27,2018at9:54
M.JM.J
1321212bronzebadges
1
2
thatdoesn'tpreserveBCliketheanswerfrom@atmPleaseconsiderretractingorupdatingyouranswer.Thereisnoreasontoleavepython2usersbehindorhavebreakingpython3
– MrMesees
Sep4,2018at22:47
Addacomment
|
0
Ifa3rd-partylibraryusesunicodeandyoucan'tchangetheirsourcecode,thefollowingmonkeypatchwillworktousestrinsteadofunicodeinthemodule:
import
.unicode=str
Share
Improvethisanswer
Follow
answeredNov7,2021at21:37
user17242583user17242583
Addacomment
|
0
youcanusethisinpython2orpython3
type(value).__name__=='unicode':
Share
Improvethisanswer
Follow
answeredFeb24at2:24
lxgxxlxgxx
111bronzebadge
Addacomment
|
YourAnswer
ThanksforcontributingananswertoStackOverflow!Pleasebesuretoanswerthequestion.Providedetailsandshareyourresearch!Butavoid…Askingforhelp,clarification,orrespondingtootheranswers.Makingstatementsbasedonopinion;backthemupwithreferencesorpersonalexperience.Tolearnmore,seeourtipsonwritinggreatanswers.
Draftsaved
Draftdiscarded
Signuporlogin
SignupusingGoogle
SignupusingFacebook
SignupusingEmailandPassword
Submit
Postasaguest
Name
Email
Required,butnevershown
PostYourAnswer
Discard
Byclicking“PostYourAnswer”,youagreetoourtermsofservice,privacypolicyandcookiepolicy
Nottheansweryou'relookingfor?Browseotherquestionstaggedpythonunicodepython-3.xnameerrorbidioraskyourownquestion.
TheOverflowBlog
HowtoearnamillionreputationonStackOverflow:beofservicetoothers
Therightwaytojobhop(Ep.495)
FeaturedonMeta
BookmarkshaveevolvedintoSaves
Inboximprovements:markingnotificationsasread/unread,andafiltered...
Revieweroverboard!Orarequesttoimprovetheonboardingguidancefornew...
CollectivesUpdate:RecognizedMembers,Articles,andGitLab
Shouldweburninatethe[script]tag?
Linked
11
NameError:name'unicode'isnotdefined
0
Whereisthe`unicode`classlocatedinPython?
0
HowdoIimporttheunicodefunctioninPython?
0
Convertstringtounicode-NameError:name'unicode'isnotdefined
313
Replacenon-ASCIIcharacterswithasinglespace
224
HowdoIgetthepathofthecurrentexecutedfileinPython?
81
pandas-changedf.indexfromfloat64tounicodeorstring
22
Pathnametoolongtoopen?
2
(Python)Makevariableequaltozeroifthedatatypeisnotnumeric
3
scrapy-itemloader-defaultprocessors
Seemorelinkedquestions
Related
709
Whatisthebestwaytoremoveaccents(normalize)inaPythonunicodestring?
146
pythonNameError:globalname'__file__'isnotdefined
383
NameError:globalname'xrange'isnotdefinedinPython3
2
NameError:globalname'cb'isnotdefined
12
Howtoinstallsetproctitleonwindows?
264
input()error-NameError:name'...'isnotdefined
0
Errorwhentryingtousepymysqlwithsqlalchemysre_constants.error:nothingtorepeat
HotNetworkQuestions
Interpretinganegativeself-evaluationofahighperformer
MakeaCourtTranscriber
Howtocreateamatrixofpairedvaluesfromtwomatrices?
AmIreallyrequiredtosetupanInheritedIRA?
HowdothosewhoholdtoaliteralinterpretationofthefloodaccountrespondtothecriticismthatNoahbuildingthearkwouldbeunfeasible?
UsingLaTeX/TikZforfractalflower
HowdoIsignafileusingSSHandverifyitusingacertificateauthority?
Canyoufindit?
HowtoruntheGUIofWindowsFeaturesOn/OffusingPowershell
Botchingcrosswindlandings
Doyoupayforthebreakfastinadvance?
What'sthemeaningoftheerrorproto.014-PtKathma.tez.subtraction_underflow?
Probabilisticmethodsforundecidableproblem
Howtoproperlycolorcellsinalatextablewithoutscrewingupthelines?
Findanddeletepartiallyduplicatelines
Whattranslation/versionoftheBiblewouldChaucerhaveread?
StandardCoverflow-safearithmeticfunctions
PreferenceofBJTtoMOSFET
SomeoneofferedtaxdeductibledonationasapaymentmethodforsomethingIamselling.AmIgettingscammed?
Howdoparty-listsystemsaccommodateindependentcandidates?
Doublelinemathsentence
2016PutnamB6difficultsummationproblem
Howdoyoucalculatethetimeuntilthesteady-stateofadrug?
Movingframesmethod
morehotquestions
Questionfeed
SubscribetoRSS
Questionfeed
TosubscribetothisRSSfeed,copyandpastethisURLintoyourRSSreader.
lang-py
Yourprivacy
Byclicking“Acceptallcookies”,youagreeStackExchangecanstorecookiesonyourdeviceanddiscloseinformationinaccordancewithourCookiePolicy.
Acceptallcookies
Customizesettings