2

In test.txt:

rt : objective
tr350rt : objective
rtrt : objective
@username : objective
@user_1236 : objective
@254test!! : objective
@test : objective
#15 : objective

My codes:

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], ""))

I got:

 : objective
tr350 : objective
 : objective
@username : objective
@user_1236 : objective
@254test!! : objective
 : objective
#15 : objective

I am trying to replace only "rt" and all @ with space

But from my codes all "rt" were replaced and only one @ was replaced.

I would like to get:

 : objective
tr350rt : objective
rtrt : objective
 : objective
 : objective
 : objective
 : objective
#15 : objective

Any suggestion?

4 Answers 4

2

I think regex is overkill here:

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)

produces

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

Note that I've also changed it not to overwrite the original.

Edit: if you really want to overwrite the original in-place, then I'd read the whole thing into memory first:

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)
2
  • Sorry, I am not familiar to use "with open". I have to overwrite that original file then I just use "in_fp.write(line)", right?
    – ThanaDaray
    Dec 21, 2012 at 16:05
  • 1
    Please consider taking DSM's suggestion of not overwriting the original file; this is almost always preferable. Once you're certain your code is working, you can add a bit at the end to delete the original and rename the new one to match the old name. The with open syntax just means that Python opens that file but only keeps it open within the following scope (i.e. as long as the code is indented), then automatically closes it. Dec 21, 2012 at 16:07
1
import re
with open("test.txt") as infile:
    text = infile.read()
    newtext = re.sub(r"(?m)^(?:rt\b|@\w+)(?=\s*:)", " ", text)

Explanation:

(?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)
1
  • @ThanaDaray: Did you take a look at newtext? You would need to write that into your (new) file: with open("newfile.txt", "w" as outfile: outfile.write(newtext) Dec 21, 2012 at 16:01
1

Not even necessary to use regex here:

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]
3
  • 1
    A regex solution is rarely a better solution.
    – mmgp
    Dec 21, 2012 at 16:11
  • The original problem had more complex instances of deleting "rt" than the simple "rt :" case you handle. Dec 21, 2012 at 16:19
  • According to his wanted output on the OP, this works fine. Read the "I would like to get:" section on the OP.
    – user1632861
    Dec 21, 2012 at 16:25
1

Try this,

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()
2
  • 1
    What's the purpose of the import statements here? You're not using walk or any of the other os functions. Dec 21, 2012 at 16:03
  • 1
    I like the pattern but I don't think it'll work for the OP's case, because we're not simply removing the @ symbol but the word that starts with @.
    – DSM
    Dec 21, 2012 at 16:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.