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

时间:2016-10-26 00:45:45

标签: python function dictionary turtle-graphics

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

这是两个重要的功能:

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_tower 未在 word_tower 函数中定义,我认为这是因为它是一个局部变量。我该如何访问它?

4 个答案:

答案 0 :(得分:3)

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

word_dict = word_freq_dict()

答案 1 :(得分:2)

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

而不是

word_dict = word_freq_dict()

,试试

<div id="wrapper" ng-controller="MyController" class="my-controller">
    <div id="sidebar-wrapper">
        <ul class="sidebar-nav nav-pills nav-stacked" id="menu">
            <li class = "active">
                <a href="#legislate" ng-click="getLegislators()" ><span class="fa-stack fa-lg pull-left"><i class="fa fa-user fa-stack-1x "></i></span>Legislators</a>
            </li>

答案 2 :(得分:0)

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

答案 3 :(得分:0)

尽管正如人们所指出的那样,有必要将word_freq_dict()的输出保存到变量中,但这还不足以使代码正常工作。你的下一个问题是你对turtle.up()的使用,你的评论和论证中你不明白:

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

此程序将(虚拟)笔从(虚拟)纸上抬起,这样就不会发生线条绘制,它不会移动光标也不会进行参数化。第一个调用是有意义的(只是调整你的评论),第二个调用可能应该是调用forward()而不是在旋转乌龟之后,例如通过left(90)指向页面。

我看到的其他问题是您可能想要将乌龟移动到页面的中心底部,而不是(-200,-200),并且您可能希望打印文本居中以制作合适的塔。最后,您需要对字典的结果进行排序,以便按照使用频率的顺序排列单词,而不是默认的 随机 顺序。下面,我已经解决了这些问题,并展示了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()

这不是一个完整的程序 - 需要完成更多错误检查(例如,打开文件时),需要决定如何处理混合大小写以及条带标点符号和其他调整。< / p>

以下是应用于Mark Twain引用时的输出示例:

enter image description here

(See here for the quote and the context.)