【问题标题】:How do I access a dictionary from a function to be used in another function?如何从一个函数访问字典以在另一个函数中使用?
【发布时间】: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


    【解决方案1】:

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

    word_dict = word_freq_dict()
    

    【讨论】:

      【解决方案2】:

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

      代替

      word_freq_dict
      

      ,试试

      word_dict = word_freq_dict()
      

      【讨论】:

        【解决方案3】:

        尽管正如人们所指出的,有必要将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()
        

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

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

        (See here for the quote and the context.)

        【讨论】:

          【解决方案4】:

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

          【讨论】:

          • 很公平,我的回答比较简短,但您的回答显然是正确的。
          猜你喜欢
          • 2020-10-10
          • 1970-01-01
          • 1970-01-01
          • 2019-09-24
          • 1970-01-01
          • 2020-08-04
          • 2023-03-23
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多