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」が置き換えられ、@ が 1 つだけ置き換えられました。

私は取得したい:

 : 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

ここで正規表現を使用する必要さえありません:

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 に答える
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 に答える