如何从一个函数访问要在另一个函数中使用的字典? [英] How do I access a dictionary from a function to be used in another function?

查看:162
本文介绍了如何从一个函数访问要在另一个函数中使用的字典?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于作业,我必须将字符串作为输入并将其写为文件.然后,函数从文件中获取字符串,并将每个单词放入字典中,该值是单词在字符串中出现的次数.然后,这些单词将被打印在一个塔"(类似于单词云)中,每个单词的大小取决于单词在字符串中出现的次数.

For an assignment I have to take a string as an input and write it as a file. Then, a function takes the string from the file and puts each word in a dictionary, with the value being the amount of times that word appears in the string. The words will then be printed in a "tower" (similar to a word cloud) with the size of each word based on the amount of times the word appears in the string.

这是两个重要功能:

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倍.

Let me explain the second function. I have imported turtle graphics for the tower to be formed. What I tried to do is call the word_freq_dict function into the word_tower function in order to get access to the dictionary. The reason for this is because the word has to be printed 10 times the size of the amount of times it appears in the string. The cursor then must move up 1.5 times the size of the word.

运行后,我得到的错误是 word_tower 函数中未定义 word_dict ,我认为这是因为它是局部变量.我该如何访问?

After running, the error that I get is that word_dict was not defined in the word_tower function, which I assume is because it's a local variable. How can I access it?

推荐答案

调用函数不会自动在当前名称空间中保存任何内容.您必须明确分配它.

Calling a function doesn't automatically save anything in your current namespace. You have to explicitly assign it.

word_dict = word_freq_dict()

这篇关于如何从一个函数访问要在另一个函数中使用的字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆