4

I want to replace certain lines in my text with another string. So far I was able to locate the text I want to replace with:

text = open('sample','r').read()
regex = re.compile('.*#= min, max\s')
for match in regex.finditer(text):
    print match.group(0) #this is what i want to replace

EDIT: also tried

text = open('sample','r').read().split('\n')
for line in text:
    line = re.sub('.*#= min, max\s', "HOLA", line)

The text stays the same. Could it be that my regex is messed up? I used the same one somewhere else and there was no problem. Also its a simple regex.

How do I switch it to another line? Thanks!

3
  • I guess you're looking for re.sub. docs.python.org/library/re.html#re.sub Commented Sep 12, 2012 at 8:31
  • To your edit: Of course the text stays the same. You iterate it over and modify the variable line, but drop its contents immediately. Try newtext=[re.sub('.*#= min, max\s', "HOLA", line) for line in text]. Commented Sep 12, 2012 at 8:38
  • If you liked one of these answers, can you accept one? Commented Nov 12, 2014 at 8:03

3 Answers 3

1

try:

subbedlines = []

with open('sample','r') as textreader:
    lines = textreader.read().split('\n')

for line in lines:
    subbedlines.append(re.sub('.*#= min, max\s', "HOLA", line))

should work if your regex is correct and your lines in the text file are matching. to write the file again simply do:

with open('sample','w') as textwriter:
    for line in subbedlines:
        textwriter.write("%s\n" % line)
Sign up to request clarification or add additional context in comments.

Comments

1

I am not sure if I understand what you want. But the regex objects's sub() function can be called with either the text you want to replace with, such as

regex.sub("new text", text)

or with a function taking a match object and returning the text to be replaced with, such as

def reverse(match):
    return match.group(0)[-1::-1]
    # or do whatever else you might want to do
regex.sub(reverse, text)

so that you are completely free to decide what to replace with.

Be aware that due to the greedy .* in your regex, this might replace only the last part. Be sure to work with $ (end of line), ^ (start of line), .*? (non-greedy version) and perhaps the re option MULTILINE.

1 Comment

As you can see I tried it (just edited my question), but it doesn't work and I don't know why\
0

Maybe i dont understand, but why are you iterating line after line, instead of just replacing every it like this:

import re

with open("text.txt") as text:
    new_text = re.sub("jj", "xx", text.read())
    with open("newtext.txt", "w") as result:
        result.write(new_text)

but maybe I am missing something.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.