Ошибка в Wordcloud python с generate_from_frequencies - PullRequest
0 голосов
/ 28 мая 2020

Я пытаюсь создать wordcloud с python, но обнаружил ошибку.

# This is the uploader widget

def _upload():

    _upload_widget = fileupload.FileUploadWidget()

    def _cb(change):
        global file_contents
        decoded = io.StringIO(change['owner'].data.decode('utf-8'))
        filename = change['owner'].filename
        print('Uploaded `{}` ({:.2f} kB)'.format(
            filename, len(decoded.read()) / 2 **10))
        file_contents = decoded.getvalue()

    _upload_widget.observe(_cb, names='data')
    display(_upload_widget)

_upload()

def calculate_frequencies(file_contents):
    # Here is a list of punctuations and uninteresting words you can use to process your text
    punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~'''
    uninteresting_words = ["the", "a", "to", "if", "is", "it", "of", "and", "or", "an", "as", "i", "me", "my", \
    "we", "our", "ours", "you", "your", "yours", "he", "she", "him", "his", "her", "hers", "its", "they", "them", \
    "their", "what", "which", "who", "whom", "this", "that", "am", "are", "was", "were", "be", "been", "being", \
    "have", "has", "had", "do", "does", "did", "but", "at", "by", "with", "from", "here", "when", "where", "how", \
    "all", "any", "both", "each", "few", "more", "some", "such", "no", "nor", "too", "very", "can", "will", "just"]

    # LEARNER CODE START HERE
    import csv
    from wordcloud import WordCloud
    import matplotlib.pyplot as plt

    reader = csv.reader(open('namesDFtoCSV', 'r',newline='\n'))
    d = {}
    for k,v in reader:
        d[k] = int(v)

    #Generating wordcloud. Relative scaling value is to adjust the importance of a frequency word.
    #See documentation: https://github.com/amueller/word_cloud/blob/master/wordcloud/wordcloud.py
    wordcloud = WordCloud(width=900,height=500, max_words=1628,relative_scaling=1,normalize_plurals=False).generate_from_frequencies(d)

    plt.imshow(wordcloud, interpolation='bilinear')
    plt.axis("off")
    plt.show()
    #wordcloud
    cloud = wordcloud.WordCloud()
    cloud.generate_from_frequencies()
    return cloud.to_array()

# Display your wordcloud image

myimage = calculate_frequencies(file_contents)
plt.imshow(myimage, interpolation = 'nearest')
plt.axis('off')
plt.show()

Здравствуйте, я получаю сообщение об ошибке после стольких исследований, мне не удалось найти решение, поэтому я решил разместить здесь. Это было похоже на то, как будто я приложил столько усилий, чтобы написать это, но вы знаете, что ошибка сохраняет все.

NameError                                 Traceback (most recent call last)
<ipython-input-8-fd0f708f372c> in <module>
      1 # Display your wordcloud image
      2 
----> 3 myimage = calculate_frequencies(file_contents)
      4 plt.imshow(myimage, interpolation = 'nearest')
      5 plt.axis('off')

NameError: name 'file_contents' is not defined

Пожалуйста, помогите мне в решении этой проблемы. Мне это очень нужно!

1 Ответ

0 голосов
/ 28 мая 2020

Ошибка предполагает, что функция не известна среде выполнения python.

Вы пытались сохранить все исходники в виде файла prog.py и выполнить его из командной строки с помощью python prog.py ?

...