1

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]$ 
2

2 Answers 2

0

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]$ 
Sign up to request clarification or add additional context in comments.

Comments

0

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.

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.