Search code examples
pythonregexpython-2.7raw-input

Counting the number of lines that special characters appear in a txt file from user input (Python 2.7)


Using Python 2.7, I am trying to create a program that simulates the grep search command in Unix. In other words, I want to ask the user to enter a regular expression and then subsequently count the number of lines where the user's inputted regular expression appears in the file.

This is my code which I already know is totally messed up (I've been at this problem for hours now, and I am at my wit's end). In this code, I entered the string "^Author" which returned 0 lines when it should have returned approximately 1798 lines from the file that I have decided to open (the "what.txt" file):

import re
hand = open('what.txt')
yo = raw_input("Enter a regular expression: ")
count = 0
for line in hand:
    x = re.findall('.*[a-zA-Z]+.*', line)
    if yo in line and len(x) > 0:
        count += 1

print "what.txt had", count, "lines that matched %s" % yo

I am drawing a blank and haven't been able to find answers relating to this problem on StackOverflow. In short, any help would be awesome.


Solution

  • You're not actually using your regex in your search at the moment.

    x = re.findall(yo, line)
    if x:
        count += 1 # multiple non-overlapping occurences on one line
    
    print "what.txt had {0} lines that matched {1}".format(count, yo)