텍스트 본문 안에있는 26 개의 글자 수를 사전에 누적해야합니다. 사용자가 글자를 입력 할 때 글자의 빈도를 텍스트 내에 표시해야합니다. 이 일에 어떻게 가야합니까?dict python에서 키를 얻는 방법
import urllib2
import numpy as py
import matplotlib
response = urllib2.urlopen('http://students.healthinformaticshub.ca/jane-austen-sense-n-sensibility.txt')
alphabet = 'abcdefghijklmnopqrstuvwxyz'
# initialize the dict we will use to store our
# counts for the individual vowels:
alphabet_counts = {'a': 0, 'b': 0, 'c': 0, 'd': 0, 'e': 0, 'f': 0, 'g': 0, 'h': 0,\
'i': 0, 'j': 0, 'k': 0, 'l': 0, 'm': 0, 'n': 0, 'o': 0, 'p': 0, 'q': 0, 'r': 0, 's': 0,\
't': 0, 'u': 0, 'v': 0, 'w': 0, 'x': 0, 'y': 0, 'z': 0}
total_letter_count = 0
# loop thru line by line:
for line in response:
line = line.lower()
for ch in line:
if ch in alphabet:
alphabet_counts[ch] += 1
total_letter_count += 1
print('# of a\'s: ' + str(alphabet_counts['a']))
print('# of b\'s: ' + str(alphabet_counts['b']))
print('# of c\'s: ' + str(alphabet_counts['c']))
print('# of d\'s: ' + str(alphabet_counts['d']))
print('# of e\'s: ' + str(alphabet_counts['e']))
print('# of f\'s: ' + str(alphabet_counts['f']))
print('# of g\'s: ' + str(alphabet_counts['g']))
print('# of h\'s: ' + str(alphabet_counts['h']))
print('# of i\'s: ' + str(alphabet_counts['i']))
print('# of j\'s: ' + str(alphabet_counts['j']))
print('# of k\'s: ' + str(alphabet_counts['k']))
print('# of l\'s: ' + str(alphabet_counts['l']))
print('# of m\'s: ' + str(alphabet_counts['m']))
print('# of n\'s: ' + str(alphabet_counts['n']))
print('# of o\'s: ' + str(alphabet_counts['o']))
print('# of p\'s: ' + str(alphabet_counts['p']))
print('# of q\'s: ' + str(alphabet_counts['q']))
print('# of r\'s: ' + str(alphabet_counts['r']))
print('# of s\'s: ' + str(alphabet_counts['s']))
print('# of t\'s: ' + str(alphabet_counts['t']))
print('# of u\'s: ' + str(alphabet_counts['u']))
print('# of v\'s: ' + str(alphabet_counts['v']))
print('# of w\'s: ' + str(alphabet_counts['w']))
print('# of x\'s: ' + str(alphabet_counts['x']))
print('# of y\'s: ' + str(alphabet_counts['y']))
print('# of z\'s: ' + str(alphabet_counts['z']))
resp = '''
1.) Find probability of a particular letter of the alphabet
2.) Show the barplot representing these probabilities for the entire alphabet
3.) Save that barplot as a png file
4.) Quit'''
클래스 ['collections.Counter']를 살펴 보자 (https://docs.python.org/ :
이 주파수를 얻으려면, 당신은 카운터 값의 합을 알 필요가 2/library/collections.html # collections.Counter). 이 코드를 사용하여 내부 루프 전체를 대체 한 다음 사전에없는 모든 키를 삭제할 수 있어야합니다. 또는 카운터에 전달할 때 문자가 아닌 문자를 줄에서 제외 할 수 있습니다. –