试图在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
答案 0 :(得分: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))