#-------------------------------------------------------------------------------
# Name: module1
# Purpose:
#
# Author: penglaixy
#
# Created: 19/09/2013
# Copyright: (c) penglaixy 2013
# Licence: <your licence>
#-------------------------------------------------------------------------------
import string
import sys
def test(did_pass):
'''print the result of a test '''
linenum=sys._getframe(1).f_lineno
if did_pass:
msg = "Test at line{0} ok".format(linenum)
else:
msg = "Test at line{0} failed".format(linenum)
print msg
def readposint():
'''
prompt the user for a positive integer
'''
try:
value_get = int(raw_input("Enter a postive value:"))
if value_get < 0:
raise ValueError("{0} is not a valid value.".format(value_get))
except:
print "I am not going to crash, value is invalid"
def letter_counts():
letter_tab = {}
str = raw_input("Please input a string with letters: a-zA-Z:")
for al in str:
if al not in string.letters:
continue
al = string.lower(al)
letter_tab[al] = letter_tab.get(al, 0) + 1
al_keys = list(letter_tab.keys())
al_keys.sort()
for al in al_keys:
print al, " ", letter_tab[al]
return
def add_fruit(inventory, fruit, quantity = 0):
inventory[fruit] = inventory.get(fruit, 0) + quantity
return
def text_to_words(the_text):
'''
return a list of words with all punctuation removed,
and all in lowercase.
'''
my_substitutions = string.maketrans(
"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!\"#$%&()*+,-./:;<=>?@[]^_'{|}~'",
"abcdefghijklmnopqrstuvwxyz ")
cleaned_text = the_text.translate(my_substitutions)
wds = cleaned_text.split()
return wds
def get_words_in_book(filename):
'''
Read a book from filename, and return a list of its words.
'''
f = open(filename,'r')
content = f.read()
f.close()
wds = text_to_words(content)
wds.sort()
return wds
def alice_words():
wds_table = {}
idx = None
wds_list = get_words_in_book("alice_in_wonderland.txt")
for wds in wds_list:
wds_table[wds] = wds_table.get(wds, 0) + 1
al_list = list(wds_table.keys())
al_list.sort()
f = open("alice_words.txt","w")
f.write("Word Count\n")
f.write("=======================\n")
for al in al_list:
str_get = "{0:<18}{1:<5}\n".format(al, wds_table[al])
f.write(str_get)
f.close()
for (ix,al) in enumerate(al_list):
if idx == None:
idx = ix
else:
if len(al_list[ix]) > len(al_list[idx]):
idx = ix
print "The longest word in Alice in Wonderland is {0}, and it has {1} charactors".\
format(al_list[idx], len(al_list[idx]))
return
def main():
readposint()
letter_counts()
new_inventory = {}
add_fruit(new_inventory, "strawberries", 10)
test("strawberries" in new_inventory)
test(new_inventory["strawberries"] == 10)
add_fruit(new_inventory, "strawberries", 25)
test(new_inventory["strawberries"] == 35)
alice_words()
if __name__ == '__main__':
main()
输出结果 alice_words.txt的下载地址 :http://download.csdn.net/detail/penglaixy/6290293