aboSamoor / polyglot

Multilingual text (NLP) processing toolkit
http://polyglot-nlp.com
Other
2.31k stars 337 forks source link

ZeroDivisionError: float division by zero #113

Open web64 opened 7 years ago

web64 commented 7 years ago

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.

w32 commented 6 years ago

I've got some error on version polyglot==16.7.4/python3.4

chubakur commented 6 years ago

same in '16.07.04'/python 3.5

MiliasV commented 6 years ago

Same in python 3.6

elben10 commented 4 years ago

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))
Meorge commented 1 year ago

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)