Definitely you can reduce the code to pretty much two lines. But readability might be an issue if you don't know python syntax
import string
all_words = 'this is me'
print("there is:\n {0}".format('\n'.join([letter+':'+str(all_words.count(letter) + all_words.count(letter.lower())) for letter in string.uppercase])))
其他提示
There are various answers - certainly, as you wrote out letter_X = all_words.count('X') for the tenth time you should have been thinking "perhaps a for loop would save me from this?" And it would:
import string
for character in string.ascii_lowercase:
...
Similarly:
"Rather than lots of separate variables, could I use a dict with the letter as the key and the count as a value?"
"Do I need to store all of these, thenprint them, or could I just print them straight away?"
However, the simplest thing to do here is use collections.Counter, for example:
This way you only process the string once, instead of counting for every letter. Counter is basically a dictionary with some extra useful features.
Also, you need to consider case - should "A" count as "a", or vice versa, or are they separate?
Use for loops. An example for a for loop that would count the letters 'a' and 'b':
for character in "ab":
print(character + " has " + str(all_words.count(character)) + " occurences.")
If you don't want to user collection.Counter and other libraries (such as string.ascii_uppercase) and build your own algorithm, you can try this:
all_words = 'asasasaassasaasasasasassa'
upper_words = all_words.upper()
letter_freq = {}
for letter in set(upper_words):
l etter_freq[letter] = upper_words.count(letter)
for letter in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ':
print '%s: %d'%(letter, letter_freq.get(letter, 0))