Regex: Perl to Python

Terry Reedy tjreedy at udel.edu
Sun Mar 6 23:48:47 EST 2016


On 3/6/2016 11:38 PM, Fillmore wrote:
>
> Hi, I'm trying to move away from Perl and go to Python.
> Regex seems to bethe hardest challenge so far.
>
> Perl:
>
> while (<HEADERFILE>) {
>      if (/(\d+)\t(.+)$/) {
>      print $1." - ". $2."\n";
>      }
> }
>
> into python
>
> pattern = re.compile(r"(\d+)\t(.+)$")
> with open(fields_Indexfile,mode="rt",encoding='utf-8') as headerfile:
>      for line in headerfile:
>          #sys.stdout.write(line)
>          m = pattern.match(line)
>          print(m.group(0))
>      headerfile.close()

Delete this line.  Files opened in a with statement are automatically 
closed when exiting the block.  This is a main motivator and use for the 
with statement.

> but I must be getting something fundamentally wrong because:
>
> Traceback (most recent call last):
>    File "./slicer.py", line 30, in <module>
>      print(m.group(0))
> AttributeError: 'NoneType' object has no attribute 'group'
>
>
>   why is 'm' a None?

Python has a wonderful interactive help facility.  Learn to use it.

 >>> import re
 >>> help(re.match)
Help on function match in module re:

match(pattern, string, flags=0)
     Try to apply the pattern at the start of the string, returning
     a match object, or None if no match was found.
 >>>

Add 'if m is not None:' before accessing m.group.

-- 
Terry Jan Reedy




More information about the Python-list mailing list