0
試圖讓Python中的 'sed的替換' 功能工作Python的應用re.sub工作不正常
我有什麼現在
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}',這顯然是無效的。 – millimoose