[Tutor] Tutor Digest, Vol 152, Issue 3

Alan Gauld alan.gauld at yahoo.co.uk
Sun Oct 2 05:47:05 EDT 2016


On 02/10/16 03:50, anish singh wrote:

>> Possibly, but we can't tell because
>> a) You don't show us the code that parses your input

Thanks, that helps.

> import os, sys, getopt
> import re
> import glob
> 
> 
> def get_full_path(path, pattern):
>   for (dirpath, dirnames, filenames) in os.walk(path):
>     match = re.search(pattern, dirpath)
>     for filename in filenames:
>       if filename.endswith(('.c', '.h')):
>         yield os.path.join(dirpath, filename)

> def read_file(file, pattern):
>   with open(file, 'r') as infile:
>     for line in infile:
>       match = re.compile(str(pattern)).match(line)

match() only matches at the beginning of a line.
Are you sure you don't want search() which will
find your pattern anywhere on the line?

Also compiling the regex each time round is
wasteful, you should use compile before
the loop:

regex = re.compile(str(pattern))  # do it once
for line in infile:
    match = regex.match(line)

Finally, you shouldn't need the str() call
since your input arguments should already
be strings.

>       if match:
>         print(file + " " + match.group())
> 
> def main(argv):
>   path, f_pattern, s_pattern = '', '', ''
>   try:
>     opts, args =
> getopt.getopt(argv,"hi:p:f:s:",["ifile=","file_pattern=","string_pattern="])
>   except getopt.GetoptError:
>     print 'test.py -i <path> -p <pattern>'
>     sys.exit(2)
> 
>   for opt, arg in opts:
>     if opt == '-h':...
>     elif opt in ("-i", "--ifile"):...
>     elif opt in ("-f", "--file_pattern"):...
>     elif opt in ("-s", "--string_pattern"):...

>     files = get_full_path(path, f_pattern)

Are you sure that line should be part of the opt for loop?

>     for file in files:
>       read_file(file, s_pattern)

> output is only file names. I don't see any other output.

Have you tested your regex function on a string
that you know should match? eg at the interpreter?
Without seeing your files it's hard to tell whether
your regex is right or wrong, but that's what I
would suspect - that it returns an empty string.

Maybe try using a simpler pattern to test it?
Something without any wildcard patterns, say?

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list