Advertisement
oldmagi

Chapter 7

Sep 14th, 2012
662
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.90 KB | None | 0 0
  1. #Exercise 7.1 Write a program to read through a file and print the contents of the file (line by line) all in upper case.
  2. user_input=input('Enter a File name:')
  3. try:
  4.     fin=open(user_input)
  5.     for line in fin:
  6.         print(str.upper(line),end='')
  7.     fin.close()
  8. except:
  9.     print('File doesn\'t exist')
  10.  
  11. --------------------------------------------------------------------------------------------------------------
  12. #Exercise 7.2 Write a program to prompt for a file name, and then read through the file and look for lines of the form:
  13. def spamcount(a,b):
  14.     for line in a:
  15.         l=line.split()
  16.         if l==[]:continue
  17.         if 'X-DSPAM-Confidence:'not in l[0]:continue
  18.         b.append(l[1])
  19.     return b
  20.    
  21. ui=input('Enter a File name:')
  22. lis=[]
  23. j=0
  24. try:
  25.     fin=open(ui)
  26.     spamcount(fin,lis)
  27.     for i in lis:
  28.         j=float(i)+j
  29.     print('Average Spam Confidence: ',format(j/len(lis),'.12g'))
  30.     fin.close()
  31. except:
  32.     print('Oops......file doesn\'t exist')
  33.  
  34. --------------------------------------------------------------------------------------------------------------
  35. #Exercise 7.3 Sometimes when programmers get bored or want to have a bit of fun, they add a harmless Easter Egg to their program (en.wikipedia.org/wiki/Easter_egg_(media)). Modify the program that prompts the user for the file name so that it prints a funny message when the user types in the exact file name ’na na boo boo’. The program should behave normally for all other files which exist and don’t exist.
  36. user=input("Enter a File name:")
  37. try:
  38.     count=0
  39.     fin=open(user)
  40.     for line in fin:
  41.         if line.startswith('Subject'):
  42.             count+=1
  43.     fin.close()
  44.     print('There were %d subject lines in '% count+'%s' % user)
  45. except:
  46.     if user=='na na boo boo':
  47.         print("NA NA BOO BOO TO YOU - You have been punk'd!")
  48.     else:
  49.         print("File cannot be opened: ",user)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement