在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