在test.txt的:如何替換文件中的單詞?
rt : objective
tr350rt : objective
rtrt : objective
@username : objective
@user_1236 : objective
@254test!! : objective
@test : objective
#15 : objective
我的代碼:
import re
file3 = 'C://Users/Desktop/test.txt'
rfile3 = open(file3).read()
for altext in rfile3.split("\n"):
saltext = altext.split("\t")
for saltword in saltext:
ssaltword = saltword.split(" ")
if re.search(r'^rt$', ssaltword[0]):
print ssaltword[0], ssaltword[2]
testreplace = open(file3, 'w').write(rfile3.replace(ssaltword[0], ""))
if re.search(r'^@\w', ssaltword[0]):
print ssaltword[0], ssaltword[2]
testreplace = open(file3, 'w').write(rfile3.replace(ssaltword[0], ""))
我:
: objective
tr350 : objective
: objective
@username : objective
@user_1236 : objective
@254test!! : objective
: objective
#15 : objective
我試圖取代只有 「RT」,所有與@空間
但從我的代碼中,所有「rt」被替換,只有一個@被替換。
我想獲得:
: objective
tr350rt : objective
rtrt : objective
: objective
: objective
: objective
: objective
#15 : objective
什麼建議嗎?
對不起,我不熟悉「with open」。我必須覆蓋原始文件,然後使用「in_fp.write 「),對嗎? – ThanaDaray
請考慮讓帝斯曼的建議不要覆蓋原始文件;這幾乎總是可取的。一旦你確定你的代碼正在工作,你可以在最後添加一點刪除原來的文件並重命名新的匹配舊名稱。 'with open'語法只是意味着Python會打開該文件,但只會在下面的範圍內保持打開狀態。只要代碼縮進),然後自動關閉它。 –
@DSM非常感謝。 – ThanaDaray