P4E Chapter 11 | Coursera Community
Coursera Header
Question

P4E Chapter 11

  • 30 July 2020
  • 0 replies
  • 32 views

Badge +1

I recently joined ‘Using Python to Access Web Data’ as a part of Python for Everybody Specialization.  While I was reading and following along chapter-11 of the book - Python for Everybody, I came accross Exercise-1 at the end of the chapter. as under:

Exercise 1: Write a simple program to simulate the operation of the
grep command on Unix. Ask the user to enter a regular expression and
count the number of lines that matched the regular expression:


$ python grep.py
Enter a regular expression: ^Author
mbox.txt had 1798 lines that matched ^Author


$ python grep.py
Enter a regular expression: ^Xmbox.
txt had 14368 lines that matched ^X-


$ python grep.py
Enter a regular expression: java$
mbox.txt had 4175 lines that matched java$

I could write the solution, which worked correctly for first two values viz. ^Author and ^X-, but for the last step viz. java$ I am not getting 4175 lines but 4218 lines in mbox.txt.

My question is am I doing anything incorrect?   My code is as under:

import re 

regex = input('Enter a regular expression: ')

fh = open('mbox.txt')
line_count = 0

for line in fh: 
    line = line.rstrip()
    if re.search(regex, line): line_count +=1
   

fh.close()

print('mbox.txt had', line_count, 'that matched', regex)
 


0 replies

Be the first to reply!

Reply