Garett Garett - 1 year ago 46
Perl Question

How to find specific strings using regular expressions and request to change them in Python?

So I am having an issue in Python. I have a huge text file with output from some machines and the machines use row names, columns, and numbers to test the equipment. Well every test was off by one row. I need Python to search the whole txt file for all rows beginning with

Site_
and when it finds those rows I need it to add one to the row portion of text. example of the line is
(Site_1,-5,33) site_1
is
$rowlabel -5
is
$row
and
33
is the
$column
. I need Python to add 1 to every
$row
.

I have the code for it written in Perl from a coworker but I need it in Python. I am posting Perl code below:

use strict;
use warnings;
my $data;
my ($rowlabel, $row, $col);
my $newrow;

open (INFILE, "160933701t.kdf") or die;
open (OUTFILE, "probe_fix.txt") or die;
while(<INFILE>)
{
chomp($_);
if ($_ =~ m/Site_/)
{
($rowlabel, $row, $col) = split(",", $_);
$newrow = $row - 1;
print OUTFILE "$rowlabel,$newrow,$col\n";
}
elsif ($_ =~ m/Row/)
{
($rowlabel, $row) = split(",", $_);
$newrow = sprintf("%.4e", $row + 1);
print OUTFILE "$rowlabel, $newrow\n";
}
else
{
print OUTFILE "$_\n";
}
}
close(INFILE);
close(OUTFILE);

Answer Source

If you really want to increment your “row portion” instead of decrementing it as it is stated in your perl code, then you can use python code like this:

INFILE="160933701t.kdf"
OUTFILE="probe_fix.txt"

f_out = open(OUTFILE, 'w')
f_out.truncate()
with open(INFILE) as f_in:
   for line in f_in:
      line = line.rstrip('\n')
      if( line[:5] == 'Site_' ): # no need for the regexp in this case
         (rawlabel, row, col) = line.split(',')
         row = str( int(row) + 1 )
         output_line = ','.join( [ rawlabel, row, col ] )
      else:
         output_line = line
      f_out.write( output_line + '\n' )
f_out.close()