本文の中の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'''
はhttps://docs.python.org/([ 'collections.Counter']クラスを見てみましょう2/library/collections.html#collections.Counter)。それを使用して内部ループ全体を置き換えてから、辞書にないすべてのキーを破棄する必要があります。また、カウンターに渡すときに、行から文字以外の文字を除外することもできます。 –