2015-11-02 49 views
0

我有以下代碼可以找到拼字遊戲字典中每個單詞的所有字母。我想用matplotlib製作一個直方圖來顯示x軸上的字形的大小,但我真的不知道從哪裏開始。我相信我需要將字符串值轉換爲整數,但我不知道如何將字典字符串值轉換爲整數。如何使用matplotlib製作顯示x軸上項目數的直方圖?

謝謝!

# import libraries 
import urllib2 
from collections import defaultdict 

#function for inputing words 
def load_dictionary(word_dictionary): 
    for word in word_dictionary: 
     yield word.strip() 

#function for making anagrams 
def make_anagrams(source): 
    d = defaultdict(list) 
    for word in source: 
     key = "".join(sorted(word)) 
     d[key].append(word) 
    return d 

#function for printing anagrams 
def print_anagrams(word_input): 
    count=0 
    n=0 
    k='' 
    d = make_anagrams(word_input) 
    for key, anagrams in d.iteritems(): 
     if len(anagrams) > 1: 
      count+= 1 
      if n < len(anagrams): 
       n=len(anagrams) 
       k=key 
    print 'The number of unique anagrams is: %d:' % count 
    print 'The largest group of anagrams for a word is: %d; and the original word is: %s' % (n , k) 
    print 'The anagrams for the largest anagram word is: %s ' % d[k] 


#input dictionary from puzzlers.org    
word_dictionary = urllib2.urlopen('http://www.puzzlers.org/pub/wordlists/ospd.txt') 
word_input = load_dictionary(word_dictionary) 
#print answer 
print_anagrams(word_input) 

回答

0

您可以使用計數器從收集模塊。以下是繪製直方圖的代碼的修改版本:

# import libraries  
import urllib2  
from collections import defaultdict  
from collections import Counter  
from matplotlib import pylab as plt  

#function for inputing words  
def load_dictionary(word_dictionary):  
    for word in word_dictionary:  
     yield word.strip()  

#function for making anagrams  
def make_anagrams(source):  
    d = defaultdict(list)  
    for word in source:  
     key = "".join(sorted(word))  
     d[key].append(word)  
    return d  

#function for printing anagrams  
def print_anagrams(word_input):  
    count=0  
    n=0  
    k=''  
    d = make_anagrams(word_input)  
    anagramLens =Counter()  
    for key, anagrams in d.iteritems():  
     anagramLens[len(anagrams)] += 1  
     if len(anagrams) > 1:  
      count+= 1  
      if n < len(anagrams):  
       n=len(anagrams)  
       k=key  
    print 'The number of unique anagrams is: %d:' % count  
    print 'The largest group of anagrams for a word is: %d; and the original word is: %s' % (n , k)  
    print 'The anagrams for the largest anagram word is: %s ' % d[k]  
    #print list(anagramLens.elements())  
    plt.figure()  
    n, bins, patches = plt.hist(list(anagramLens.elements()), histtype='bar', rwidth=0.8)  
    plt.show()  
#input dictionary from puzzlers.org     
word_dictionary = urllib2.urlopen('http://www.puzzlers.org/pub/wordlists/ospd.txt')  
word_input = load_dictionary(word_dictionary)  
#print answer  
print_anagrams(word_input) 
+0

謝謝Shahram! – Andrew

相關問題