Reading Notes: proficient in Regular Expressions
TXT file
#mail.txt From Xihaode o dfsfsa Received: womenshiw To: xiaopengyou@126.com (Xiao Peng)From: dapengyou@qq.com (Da Peng)Date: 05/02/2000 at 04:58:50Subject: Re: Using the mod() function with negative numbersThanks very much for sorting this out. I had worked out how it was arriving at the result, but did not know whether it was correct. We had also tried it in Lotus 1-2-3 and the result given was -40, which was what the user expected. Nice to have built some user confidence in Excel.HiHi
Code
# Mail. PY python2.7 # use a regular expression to process the mail ''' tip: 1. When you directly read the file, a newline character '\ n' is always added to each line, you can use rstrip to process the values of the two headers and use regular expressions. '''import re try: F = open('mail.txt ', 'R') handle T ioerror, E: E. messageflag = 1 text = ''textt ='' redate = R' ^ date :(. *) 'refrom = R' ^ From :(. *) 'reto = R' ^ :(. *) \ s *\((. *) \) 'sendtoname = ''for line in F: line = line. rstrip ('\ n') If line and flag: # Find the time sender and receiver for information processing if Re. match (redate, line, re. i): print line Elif re. match (refrom, line, re. i): print line Elif re. match (Reto, line, re. i): print line sendto = Re. findall (Reto, line, re. i) sendtoname = sendto [0] [1] Elif (not line) and flag: Flag = 0 # When there is a blank line, the flag becomes 0, put all the parts after the text into the text. Else: Text + = line + '\ n' print' \ NHI, ', sendtoname,': 'print textf. close ()