2017-04-18 1 views
-1

텍스트 본문 안에있는 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''' 
+0

클래스 ['collections.Counter']를 살펴 보자 (https://docs.python.org/ :

이 주파수를 얻으려면, 당신은 카운터 값의 합을 알 필요가 2/library/collections.html # collections.Counter). 이 코드를 사용하여 내부 루프 전체를 대체 한 다음 사전에없는 모든 키를 삭제할 수 있어야합니다. 또는 카운터에 전달할 때 문자가 아닌 문자를 줄에서 제외 할 수 있습니다. –

답변

0

난 당신이 정말 원하는 것을 확실하지 않다, 당신은 단지 학습하기 때문에 :

이 지금까지 내 코드입니다. 나는 대답보다는 힌트를 당신에게 줄 것이다. dict 개체에는 itemsiteritems이라는 메서드가 있습니다. 키와 값을 모두 얻으려면. 주어진 문자를지고의 확률을 계산하려면이 iteritems를 사용할 수 있습니다

char_probabilities = dict() 
for character, count in alphabet_counts.iteritems(): 
    # compute probability given the 
    # frequency of character her you can use the 
    # sum builtin and values method on the dict 
    char_probabilities[character] = [YOU DO SOME WORK] 
0

나는 코드의 일부를 정리하고 나 또한 당신을 기반으로 파이썬 2.7을 사용하고 있기 때문에 (raw_input을 사용하는 방법에 대한 예를 추가하여 urllib2가의 사용) :

import collections, urllib2, contextlib 

url = 'http://students.healthinformaticshub.ca/jane-austen-sense-n-sensibility.txt' 
alphabet_counts = collections.Counter() 
with contextlib.closing(urllib2.urlopen(url)) as response: 
    for line in response: 
     alphabet_counts.update(x for x in line.lower() if x.isalpha()) 

이 카운터는입니다 :

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 = {letter: 0 for letter in alphabet} 

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 

for letter in alphabet_counts: 
    print('# of ' + letter + '\'s: ' + str(alphabet_counts[letter])) 

letter = raw_input("Enter a character: ") 
print('# of ' + letter + '\'s: ' + str(alphabet_counts[letter])) 

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''' 
0

이것은 Counter 클래스의 교과서를 사용 것 같아하위 클래스는 원래 alphabet_counts처럼 작동하지만 사용자의 노력은 훨씬 적습니다. 입력 스트림을 닫으려는 것을 염두에 두십시오. 이것이 내가 with 블록을 사용하는 이유입니다.

total_letters = sum(alphabet_counts.values()) 
frequencies = {letter: float(count)/total_letters for count, letter in alphabet_counts.iteritems()} 
관련 문제