AttributeError: объект 'dict' не имеет атрибута 'translate' - PullRequest
0 голосов
/ 03 августа 2020

У меня проблема с этим фрагментом кода, это упражнение, в котором мне нужно настроить облако слов, улавливая частоту слов в тексте.

Мне удалось убрать пунктуации с помощью map и translate, затем я превратил их все в более низкие строки и проверил их частоту с помощью a для l oop.

Когда я пытаюсь передать их генератору wordcloud, я получаю сообщение об ошибке: AttributeError : объект 'dict' не имеет атрибута 'translate'


    import string
    
    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
        word_listing=[]
        container = {}
    
        table = str.maketrans(dict.fromkeys(string.punctuation)) #Removing punctuation first
        file_contents = file_contents.translate(table)  
        #-------------------------------------------------------------------------------
        file_contents=file_contents.split()                                
        file_contents=map(str.lower,file_contents) #making lower string
        file_contents=list(file_contents)
        #-------------------------------------------------------------------------------
        for item in file_contents:
            if item not in (uninteresting_words): #removing uninteresting words 
                
                container[item]=item
                word_listing.append(item) 
                #setting up frequency count
    
                for i in word_listing: 
                    container[i] = 0
                for i in word_listing:
                    container[i] += 1
    
        #wordcloud
        cloud = wordcloud.WordCloud()
        cloud.generate_from_frequencies(container)
        return cloud.to_array()

Все работает нормально, проблема возникает, когда я его устанавливаю:


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

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

<ipython-input-13-0620c3cd20f5> in calculate_frequencies(file_contents)
     15 
     16     table = str.maketrans(dict.fromkeys(string.punctuation)) #Removing punctuation first
---> 17     file_contents = file_contents.translate(table)
     18     #-------------------------------------------------------------------------------
     19     file_contents=file_contents.split()

AttributeError: 'dict' object has no attribute 'translate'

Мне нужно помогите понять, почему это происходит и как это исправить. Всем спасибо!

...