user1601716
user1601716

Reputation: 1993

Python re.sub not working correctly

trying to get a 'sed replace' function in python working

What I have now

def pysed(filename,search,replace):    
    for line in fileinput.input(filename,inplace=True):
        sys.stdout.write(re.sub(r'{0}','{1}',line.format(search,replace)))

calling the function...

pysed('/dev/shm/FOOD_DES.txt','Butter','NEVER')

File /dev/shm/FOOD_DES.txt contains the following....

~01001~^~0100~^~Butter, salted~^~BUTTER,WITH SALT~^~~^~~^~Y~^~~^0^~~^6.38^4.27^8.79^3.87
~01002~^~0100~^~Butter, whipped, with salt~^~BUTTER,WHIPPED,WITH     SALT~^~~^~~^~Y~^~~^0^~~^6.38^4.27^8.79^3.87
~01003~^~0100~^~Butter oil, anhydrous~^~BUTTER OIL,ANHYDROUS~^~~^~~^~Y~^~~^0^~~^6.38^4.27^8.79^3.87
~01004~^~0100~^~Cheese, blue~^~CHEESE,BLUE~^~~^~~^~Y~^~~^0^~~^6.38^4.27^8.79^3.87
~01005~^~0100~^~Cheese, brick~^~CHEESE,BRICK~^~~^~~^~Y~^~~^0^~~^6.38^4.27^8.79^3.87
~01006~^~0100~^~Cheese, brie~^~CHEESE,BRIE~^~~^~~^~Y~^~~^0^~~^6.38^4.27^8.79^3.87
~01007~^~0100~^~Cheese, camembert~^~CHEESE,CAMEMBERT~^~~^~~^~Y~^~~^0^~~^6.38^4.27^8.79^3.87
~01008~^~0100~^~Cheese, caraway~^~CHEESE,CARAWAY~^~~^~~^~~^~~^0^~~^6.38^4.27^8.79^3.87
~01009~^~0100~^~Cheese, cheddar~^~CHEESE,CHEDDAR~^~~^~~^~Y~^~~^0^~~^6.38^4.27^8.79^3.87
~01010~^~0100~^~Cheese, cheshire~^~CHEESE,CHESHIRE~^~~^~~^~~^~~^0^~~^6.38^4.27^8.79^3.87

When running this however, I am getting the following error. Any thoughts, ideas?

pysed('/dev/shm/FOOD_DES.txt','Butter','NEVER')    
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in pysed
  File "/usr/lib64/python2.6/re.py", line 151, in sub
    return _compile(pattern, 0).sub(repl, string, count)
  File "/usr/lib64/python2.6/re.py", line 245, in _compile
    raise error, v # invalid expression

Upvotes: 0

Views: 625

Answers (1)

John Kugelman
John Kugelman

Reputation: 361615

You wrote:

sys.stdout.write(re.sub(r'{0}','{1}',line.format(search,replace)))

This is rather confusing. Is this what you meant to write?

sys.stdout.write(re.sub('{0}'.format(search), '{0}'.format(replace), line))

That would of course be equivalent to:

sys.stdout.write(re.sub(search, replace, line))

Upvotes: 1

Related Questions