【发布时间】:2016-10-26 00:45:45
【问题描述】:
对于作业,我必须将字符串作为输入并将其写入文件。然后,一个函数从文件中获取字符串并将每个单词放入字典中,值是该单词在字符串中出现的次数。然后将单词打印在“塔”中(类似于单词云),每个单词的大小取决于单词在字符串中出现的次数。
这是两个重要的功能:
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 函数中定义,我认为这是因为它是一个局部变量。如何访问它?
【问题讨论】:
标签: python function dictionary turtle-graphics