Repository: amueller/word_cloud

Issue:
Checking 'frequencies' list in function WordCloud.generate_from_frequencies()
I'm having an issue related to the generation of the word_cloud from a list of frequencies per word. As you can see below, the function is trying to retrieve the max frequency from a list 'frecuencies', but it doesn't check before if there is some element in that list:

https://github.com/amueller/word_cloud/blob/master/wordcloud/wordcloud.py#L350

That kind of check is done after, in the following snippet (but it's too late, because we already tried to access to the first element on a probably empty list):

https://github.com/amueller/word_cloud/blob/master/wordcloud/wordcloud.py#L360-L362

In my own version, I've done the following correction related to the first snippet in order to avoid some crashes (just as an example):

``` 
        try:
            max_frequency = float(frequencies[0][1])
        except:
            print "ERROR with list 'frecuencies'=", frequencies
```

Best regards!



Discussion:

Patch:
diff --git a/wordcloud/wordcloud.py b/wordcloud/wordcloud.py
index ae5d107..e63d922 100644
--- a/wordcloud/wordcloud.py
+++ b/wordcloud/wordcloud.py
@@ -348,7 +348,11 @@ class WordCloud(object):
         """
         # make sure frequencies are sorted and normalized
         frequencies = sorted(frequencies.items(), key=item1, reverse=True)
+        if len(frequencies) <= 0:
+            raise ValueError("We need at least 1 word to plot a word cloud, "
+                             "got %d." % len(frequencies))
         frequencies = frequencies[:self.max_words]
+
         # largest entry will be 1
         max_frequency = float(frequencies[0][1])
 
@@ -360,10 +364,6 @@ class WordCloud(object):
         else:
             random_state = Random()
 
-        if len(frequencies) <= 0:
-            print("We need at least 1 word to plot a word cloud, got %d."
-                  % len(frequencies))
-
         if self.mask is not None:
             mask = self.mask
             width = mask.shape[1]


Test patch:
diff --git a/test/test_wordcloud.py b/test/test_wordcloud.py
index ee91f2e..2d2662b 100644
--- a/test/test_wordcloud.py
+++ b/test/test_wordcloud.py
@@ -76,6 +76,16 @@ def test_multiple_s():
     assert_in("flosss", wc.words_)
 
 
+def test_empty_text():
+    # test originally empty text raises an exception
+    wc = WordCloud(stopwords=[])
+    assert_raises(ValueError, wc.generate, '')
+
+    # test empty-after-filtering text raises an exception
+    wc = WordCloud(stopwords=['a', 'b'])
+    assert_raises(ValueError, wc.generate, 'a b a')
+
+
 def test_default():
     # test that default word cloud creation and conversions work
     wc = WordCloud(max_words=50)