ami91
ami91

Reputation: 1354

Type error in Python: need a single Unicode character as parameter

When I try to convert a unicode variable to float using unicodedata.numeric(variable_name), I get this error "need a single Unicode character as parameter". Does anyone know how to resolve this?

Thanks!

Here is the code snippet I'm using :

f = urllib.urlopen("http://compling.org/cgi-bin/DAL_sentence_xml.cgi?sentence=good")
s = f.read()
f.close()
doc = libxml2dom.parseString(s)
measure = doc.getElementsByTagName("measure")
valence = unicodedata.numeric(measure[0].getAttribute("valence"))        
activation = unicodedata.numeric(measure[0].getAttribute("activation"))

This is the error I'm getting when I run the code above

Traceback (most recent call last):
File "sentiment.py", line 61, in <module>
valence = unicodedata.numeric(measure[0].getAttribute("valence"))        
TypeError: need a single Unicode character as parameter

Upvotes: 0

Views: 1238

Answers (1)

Dietrich Epp
Dietrich Epp

Reputation: 213578

Summary: Use float() instead.

The numeric function takes a single character. It does not do general conversions:

>>> import unicodedata
>>> unicodedata.numeric('½')
0.5
>>> unicodedata.numeric('12')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: need a single Unicode character as parameter

If you want to convert a number to a float, use the float() function.

>>> float('12')
12.0

It won't do that Unicode magic, however:

>>> float('½')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: could not convert string to float: '½'

Upvotes: 2

Related Questions