과제를 위해 나는 문자열을 입력으로 받아서 파일로 써야합니다. 그런 다음 함수는 파일에서 문자열을 가져 와서 각 단어를 사전에 넣습니다. 값은 단어가 문자열에 나타나는 시간입니다. 그러면 단어가 문자열에 나타나는 시간을 기준으로 각 단어의 크기와 함께 "타워"(단어 구름과 유사)에 단어가 인쇄됩니다. 다른 함수에서 사용할 함수에서 사전에 액세스하려면 어떻게합니까?
이
은 두 가지 중요한 기능은 다음과 같습니다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 기능에 정의되지 않은 것입니다. 어떻게 접근 할 수 있습니까?
페어, 내가, 내 대답은 더 짧은했습니다 그러나 당신의 대답은 분명 올바른하십시오 마크 트웨인 견적에 적용 할 때 다음
은 출력의 예 하나. –