對於一個賦值,我必須將一個字符串作爲輸入並將其寫爲一個文件。然後,函數從文件中獲取字符串,並將每個單詞放在字典中,其值是該單詞出現在字符串中的次數。這些單詞將被打印在一個「塔」(類似於一個詞雲)中,每個單詞的大小基於單詞出現在字符串中的次數。如何從函數中訪問字典以用於其他函數?
這是兩個重要的功能:
def word_freq_dict(): # function to count the amount of times a word is in the input string
file = open("data_file.txt", 'r')
readFile = file.read() #reads file
words = readFile.split() #splits string into words, puts each word as an element in a list
word_dict = {} # empty dictionary for words to be placed in with the amount of times they appear
for i in words:
word_dict[i] = word_dict.get(i,0) + 1 # adds items in "words" to a dictionary and amount of times they appear
return word_dict
和
def word_tower():
t = turtle.Turtle()
t.hideturtle() # hides cursor
t.up() # moves cursor up
t.goto(-200, -200) # starts at the -200,-200 position
word_freq_dict() #calls dictionary function
for key, value in word_dict.items():
t.write(key, font = ('Arial', value*10, 'normal'))
t.up(1.5*len(key))
讓我解釋的第二功能。我已經導入了烏龜圖形的塔形成。我試圖做的是將word_freq_dict函數放入word_tower函數中以獲得對字典的訪問權限。原因是因爲該單詞必須打印10倍於其在字符串中出現的次數的大小。光標必須上移1.5倍大小的單詞。
運行後,我得到的錯誤是word_dict在word_tower功能,我想是因爲它是一個局部變量沒有定義。我怎樣才能訪問它?
很公平,我做了我的答案更簡單,但你的答案顯然是正確的一。 –