如何从一个函数访问要在另一个函数中使用的字典?

How do I access a dictionary from a function to be used in another function?

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

这是两个重要的功能:

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[ 中定义=26=] 函数,我认为这是因为它是一个局部变量。我怎样才能访问它?

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

word_dict = word_freq_dict()

您可以将 word_freq_dict() 的 return 值放入名为 word_dict 的变量中,如下所示:

而不是

word_freq_dict

,试试

word_dict = word_freq_dict()

您需要将 word_dict 赋值给 word_freq_dict() 的结果。您正在 word_freq_dict() 中返回 word_dict,但它从未被分配。

虽然,正如人们所指出的,有必要将 word_freq_dict() 的输出保存到一个变量中,但这不足以让您的代码正常工作。你的下一个问题是你对 turtle.up() 的使用,从你的评论和论点来看,你不明白:

t.up() # moves cursor up
t.up(1.5*len(key))

这个例程将(虚拟)笔从(虚拟)纸上抬起,这样就不会画线了,它既不移动光标也不接受参数。第一次调用是有道理的(只需调整您的评论),第二次调用可能应该是 forward() 的调用,而不是在旋转海龟之后,例如通过 left(90) 指向上页。

我看到的其他问题是您可能想将乌龟移动到页面底部的中心,而不是 (-200, -200),并且您可能想打印居中的文本以制作适当的塔。最后,您需要对字典的结果进行排序,以便单词按照使用频率的顺序出现,而不是默认的 random 顺序.下面,我解决了这些问题,还展示了 defaultdict 在这种情况下如何发挥作用:

from collections import defaultdict
from turtle import Turtle, Screen

def word_freq_dict(file_name):
    """ Count the amount of times words appear in a string """

    file = open(file_name)
    readFile = file.read()  # read file
    words = readFile.split()  # splits string into words, puts each word as an element in a list
    word_dict = defaultdict(int)  # dictionary for words to be placed in with amount of times they appear

    for word in words:
        word_dict[word] += 1 # adds item in 'words' to a dictionary and amount of times it appears

    return word_dict

def word_tower(turtle, screen, file_name):

    word_dict = word_freq_dict(file_name)  # calls dictionary function

    turtle.up()  # lift pen off page
    turtle.goto(0, - screen.window_height() // 2)  # start at the center bottom of the page
    turtle.left(90)  # point turtle up the page for subsequent forward() calls

    for key in sorted(word_dict, key=lambda k: word_dict[k], reverse=True):  # sort words by frequency
        value = word_dict[key] * 15  # probably should compute this value based on # words and page height
        turtle.write(key, font=('Arial', value, 'normal'), align='center')
        turtle.forward(value)

yertle = Turtle()
yertle.hideturtle()  # hide turtle image

screen = Screen()

word_tower(yertle, screen, 'data_file.txt')

screen.exitonclick()

这不是一个完整的程序 -- 需要进行更多的错误检查(例如打开文件时),需要决定如何处理大小写混合以及去除标点符号和其他调整.

这是应用于马克吐温名言的输出示例:

(See here for the quote and the context.)