0

试图在 python 工作中获得“sed replace”功能

我现在拥有的

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)))

调用函数...

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

文件 /dev/shm/FOOD_DES.txt 包含以下内容......

~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

但是,在运行此程序时,我收到以下错误。有什么想法、想法吗?

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
4

1 回答 1

1

你写了:

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

这相当令人困惑。这是你要写的吗?

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

这当然相当于:

sys.stdout.write(re.sub(search, replace, line))
于 2012-10-02T01:30:01.687 回答