简体   繁体   中英

How to replace foo with bar in a text file using regex and python?

Simple text replacement with sed which works fine:

[nsaunders@rolly sed]$ 
[nsaunders@rolly sed]$ ll
total 8
-rwxrwxr-x. 1 nsaunders nsaunders 28 Jun  9 03:33 cmd
-rw-rw-r--. 1 nsaunders nsaunders  4 Jun  9 03:33 old
[nsaunders@rolly sed]$ 
[nsaunders@rolly sed]$ cat old 
day
[nsaunders@rolly sed]$ 
[nsaunders@rolly sed]$ cat cmd 
sed s/day/night/ <old >new

[nsaunders@rolly sed]$ 
[nsaunders@rolly sed]$ ./cmd 
[nsaunders@rolly sed]$ 
[nsaunders@rolly sed]$ ll
total 12
-rwxrwxr-x. 1 nsaunders nsaunders 28 Jun  9 03:33 cmd
-rw-rw-r--. 1 nsaunders nsaunders  6 Jun  9 03:34 new
-rw-rw-r--. 1 nsaunders nsaunders  4 Jun  9 03:33 old
[nsaunders@rolly sed]$ 
[nsaunders@rolly sed]$ cat new 
night
[nsaunders@rolly sed]$ 

How can I do something similar from mymodule ?

[nsaunders@rolly api]$ 
[nsaunders@rolly api]$ ll
total 8
-rw-rw-r--. 1 nsaunders nsaunders 48 Jun  9 03:33 client.py
-rw-rw-r--. 1 nsaunders nsaunders 63 Jun  9 03:33 mymodule.py
[nsaunders@rolly api]$ 
[nsaunders@rolly api]$ cat mymodule.py 
import re

def foo(bar):
 baz=re.compile('[a-z]+')
 return baz
[nsaunders@rolly api]$ 

thanks, NewPythonUser:

[nsaunders@rolly api]$ 
[nsaunders@rolly api]$ ll
total 8
-rw-rw-r--. 1 nsaunders nsaunders 48 Jun  9 03:44 client.py
-rw-rw-r--. 1 nsaunders nsaunders 55 Jun  9 03:52 mymodule.py
drwxrwxr-x. 2 nsaunders nsaunders 37 Jun  9 03:45 __pycache__
[nsaunders@rolly api]$ 
[nsaunders@rolly api]$ cat client.py 
import mymodule as mx

b=mx.foo("xxx")
print(b)
[nsaunders@rolly api]$ 
[nsaunders@rolly api]$ cat mymodule.py 
import re

def foo(str):
  return str.replace('x','y')
[nsaunders@rolly api]$ 
[nsaunders@rolly api]$ python3 client.py 
yyy
[nsaunders@rolly api]$ 

Use the re.sub method:

# mymodule.py

import re


def foo(foo="day", bar="night", textfile='testfile.txt'):
    with open(textfile, 'w') as wf:
        text = wf.readlines()  # "In the daytime it rains."
        wf.write(re.sub(foo, bar, text))
    return re.sub(foo, bar, text)


print(foo())

Returns:

In the nighttime it rains.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM