2

在 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

有什么建议吗?

4

4 回答 4

2

我认为正则表达式在这里有点矫枉过正:

with open("test.txt") as in_fp, open("test2.txt", "w") as out_fp:
    for line in in_fp:
        ls = line.split()
        if ls and (ls[0].startswith("@") or ls[0] == "rt"):
            line = line.replace(ls[0], "", 1)
        out_fp.write(line)

生产

localhost-2:coding $ cat test2.txt 
 : objective
tr350rt : objective
rtrt : objective
 : objective
 : objective
 : objective
 : objective
#15 : objective

请注意,我也将其更改为不覆盖原始内容。

编辑:如果您真的想就地覆盖原始文件,那么我会先将整个内容读入内存:

with open("test.txt") as fp:
    lines = fp.readlines()

with open("test.txt", "w") as out_fp:
    for line in lines:
        ls = line.split()
        if ls and (ls[0].startswith("@") or ls[0] == "rt"):
            line = line.replace(ls[0], "", 1)
        out_fp.write(line)
于 2012-12-21T16:02:44.527 回答
1
import re
with open("test.txt") as infile:
    text = infile.read()
    newtext = re.sub(r"(?m)^(?:rt\b|@\w+)(?=\s*:)", " ", text)

解释:

(?m)      # Turn on multiline mode
^         # Match start of line
(?:       # Either match...
 rt\b     # rt (as a complete word
|         # or
 @\w+     # @ followed by an alphanumeric "word"
)         # End of alternation
(?=\s*:)  # Assert that a colon follows (after optional whitespace)
于 2012-12-21T15:57:10.167 回答
1

试试这个,

import os

mydict = {"@":'',"rt":''}

filepath = 'C://Users/Desktop/test.txt'
s = open(filepath).read()
for k, v in mydict.iteritems():
    s = s.replace(k, v)
f = open(filepath, 'w')
f.write(s)
f.close()
于 2012-12-21T15:58:18.890 回答
1

甚至不需要在这里使用正则表达式:

with open("test.txt") as file:
    lines = file.readlines()
    for line in lines:
        if (line.startswith("@") and ":" in line) or line.startswith("rt :"):
            line = " :" + line.split(":", 1)[1]
于 2012-12-21T16:07:19.723 回答