# String-List-File Exercises # --------------------------------- Problem #1 --------------- def wc(filename): try: f=open(filename,'rU') s=f.read() except: return [0,0,0] chars=len(s) words=len(s.split()) lines=len(s.split('\n')) return [chars,words,lines] # ---------------------- Problem #2: ------------------------ # there are two helper functions def firstVowelPos(s): vowels='aeiouAEIOU' for i in range(len(s)): if s[i] in vowels: return i return -1 def pigify(word): letters='abcdefghijklmnopqrstuvwxyz' # remove and store trailing punctuation, if it exists if word[-1] in letters: p='' else: p=word[-1] word=word[:-1] pos=firstVowelPos(word) if pos>0: word=word[pos:]+word[:pos]+'ay' else: word+='way' # put the punctuation back word+=p return word def igpay(infile,outfile): #read the file try: f=open(infile,'rU') s=f.read() except: return # there should be a better way to indicate that we failed outlines=[] # split it into lines inlines=s.split('\n') for line in inlines: # split each line into a list of words words=line.split() outwords=[] for word in words: pigword=pigify(word) outwords.append(pigword) # create a line (string) from the pigified words outlines.append(' '.join(outwords)) # join the lines together... outs='\n'.join(outlines) # write it out try: f=open(outfile,'w') f.write(outs) f.close() except: pass return # ----------------------------- Problem #3 -------------------------- def HighLow(filename): try: f=open(filename,'rU') lines=f.read().split('\n') f.close() except: print 'Problem with opening: '+filename return if len(lines)==0: print 'no data in file' return # ignore the first line of column headers, and set up the first # versions of the answer variables: words=lines[1].split(',') highname,highgrade=words[0],int(words[1]) lowname,lowgrade=highname,highgrade # now, go through the rest of the lines: for i in range(2,len(lines)): words=lines[i].split(',') if len(words)==2: # ignore any lines without 2 words name,grade=words[0],int(words[1]) if grade>highgrade: highname,highgrade=name,grade elif grade=0: counts[pos]+=1 # now we know that, for instance, the 4th letter (which is 'd', or alpha[3]) # has occurred counts[3] times in the text # Next step: create a list of elements that look like: [counts[0],'a'], [counts[1],'b'], ... etc. pairs=[] for i in range(len(alpha)): pairs.append([counts[i],alpha[i]]) # sort it, from smallest to largest pairs.sort() pairs=pairs[::-1] # reverse the list # re-create the alphabet in decreasing rank order new_alpha='' for apair in pairs: if apair[0]>0: # include the letter only if it actually occurred in the text new_alpha+=apair[1] return new_alpha