2016-10-26 2 views
0

과제를 위해 나는 문자열을 입력으로 받아서 파일로 써야합니다. 그런 다음 함수는 파일에서 문자열을 가져 와서 각 단어를 사전에 넣습니다. 값은 단어가 문자열에 나타나는 시간입니다. 그러면 단어가 문자열에 나타나는 시간을 기준으로 각 단어의 크기와 함께 "타워"(단어 구름과 유사)에 단어가 인쇄됩니다. 다른 함수에서 사용할 함수에서 사전에 액세스하려면 어떻게합니까?

은 두 가지 중요한 기능은 다음과 같습니다

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 기능에 정의되지 않은 것입니다. 어떻게 접근 할 수 있습니까?

답변

3

함수를 호출해도 현재 네임 스페이스에있는 항목이 자동으로 저장되지 않습니다. 명시 적으로 할당해야합니다.

word_dict = word_freq_dict() 
2

당신과 같이, word_dict라는 변수에 word_freq_dict()의 반환 값을 넣을 수 있습니다 :

대신

word_freq_dict 

의, 당신은 필요

word_dict = word_freq_dict() 
0

시도의 결과에 word_dict을 지정하십시오.. word_dictword_freq_dict()에 돌려 주 겠지만 할당 된 적이 없습니다.

+0

페어, 내가, 내 대답은 더 짧은했습니다 그러나 당신의 대답은 분명 올바른하십시오 마크 트웨인 견적에 적용 할 때 다음

은 출력의 예 하나. –

0

사람들이 지적했듯이 word_freq_dict()의 출력을 변수에 저장해야하지만 코드를 작동시키는 것으로는 충분하지 않습니다.

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

이 루틴 승강기 (가상) 펜을 (가상) 종이 떨어져 더 선 그리기가 발생하지 않도록 : 당신의 다음 문제는 귀하의 의견과 주장에서, 당신이 이해하지 못하는 turtle.up()의 사용이다 커서를 움직이거나 인수를 취하지는 않습니다. 첫 번째 호출은 의미가 있습니다 (단지 의견을 조정하십시오), 두 번째 호출은 거북이를 회전 한 후 forward() 대신에 호출되어야합니다 (예 : left(90)을 통해 페이지를 가리 킵니다.

내가 본 다른 문제는 거북이를 (-200, -200)이 아닌 페이지의 가운데 아래쪽으로 옮기고 자 할 때, 아마도 텍스트를 가운데에 인쇄하여 적절한 타워를 만들고 싶을 것입니다.마지막으로, 단어가 사용 빈도 순으로 나오도록 사전 결과를 정렬해야합니다. 기본값은 입니다. - 예를 개방 할 필요가 더 오류 검사가 (거기에

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() 

이 완전한 프로그램이되지 않습니다 : 아래, 나는 defaultdict이 상황에서 도움이 될 수있는 방법을 보여 이러한 문제를 해결하고 한 파일)을 사용하는 경우 대소 문자를 혼합하여 처리하고 줄무늬를 구두점으로 처리하는 방법 및 기타 조정 방법에 대한 결정을 내릴 필요가 있습니다. 충분히

enter image description here

(See here for the quote and the context.)

관련 문제