polyglot
polyglot copied to clipboard
ZeroDivisionError: float division by zero
Great library by the way!
I frequently get this error:
File "/usr/local/lib/python3.5/dist-packages/polyglot/text.py", line 96, in polarity return sum(scores) / float(len(scores)) ZeroDivisionError: float division by zero
Locally I have replaced the line in text.py with:
if float(len(scores)) != 0: return sum(scores) / float(len(scores)) else: return 0
And that seems to work.
I've got some error on version polyglot==16.7.4/python3.4
same in '16.07.04'/python 3.5
Same in python 3.6
I've solved this problem by:
from polyglot.text import cached_property, Text
class TextOverride(Text):
@cached_property
def polarity(self):
"""Return the polarity score as a float within the range [-1.0, 1.0]
"""
scores = [w.polarity for w in self.words if w.polarity != 0]
if len(scores) == 0:
return 0.0
return sum(scores) / float(len(scores))
I ran into this situation as well. A simpler approach (that doesn't require creating a subclass) is to wrap the call to polarity
in a try
/except
block:
from polyglot.text import Text
text = Text("This is some text.")
try:
text_polarity = text.polarity
except ZeroDivisionError:
text_polarity = 0
print(text_polarity)