The Python introductory tutorial has been completed, following is the completion script: (part of the source code in the book, part of the exercise of their own)
#写一个文本统计的脚本: Calculates and prints statistical data about a text file, include the number of characters, lines, and words in the file, and the first 10 occurrences of the most occurrences of the words in order import time keep=[' A ', ' B ', ' C ', ' d ', ' e ', ' f ', ' G ', ' h ', ' I ', ' j ', ' K ', ' l ', ' m ', ' n ', ' o ', ' P ', ' Q ', ' R ', ' s ', ' t ', ' u ', ' V ', ' w ', ' x ', ' y ', ' z ', ', '-', ' ', ' stop_words=[', '
And ', ' I ', ' to ', ' of ', ' a ', ' you ', ' I ', ' that ', ' in ', ' she ', ' him ', ' her ', ' his ', ' it ', ' is ', ' was ', ' had ' def normalize (s):
Result= ' for C in S.lower (): If C in Keep:result+=c return result def make_dict (s): Words=normalize (s). Split () d={} for W in words:if W in D:d[w]+=1 else:d[w]=1 return D def file_status (f): C=open (f). Read () "using each read Take a row Fopen=open (f) c= ' for lines in Fopen:c+=line ' Print (f, ' status: ') print (' Length: ', Len (c)) print (' Number of rows: ', C.cou NT (' \ n ') print (' Number of words: ', Len (normalize (c). Split ())) d=make_dict (c) Print (' Number of words: ', sum (D[w] for W in D)) print (' Number of different words: ', len
([w for W in D]) Print (' Average word length: ', SUM (Len (w) for W in D)/sum (D[w] for W in D)) print (' Total words only once: ', Len ([D[w] for W (d if d[w]==1])) LST =[(D[W],W) for W in D] lst.sort () lSt.reverse () print (the top 10 occurrences of words and times are: ') I=1 for Count,word in Lst[:10]: print ('%d.%4d%s '% (I,count,word)) I+=1 PR Int (' Top 10 occurrences of the most number of words and times is (after removing the functional word): ') j=1 for Count,word in lst[:]: If Word isn't in Stop_words:print ('%d.%4d%s '% (J,cou Nt,word)) J+=1 if J==11:break start_time=time.time () file_status (' D:\Code\python\pg1342.txt ') end_time=time.time ( Print (' Total time: ', str (end_time-start_time))
Praise yourself for a ^^
Attached: Tutorial "Getting Started with Python programming (3rd edition)", "Add" Toby