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]$ 
  • A few suggestions: [How do I call a sed command in a python script?](https://askubuntu.com/questions/747450/how-do-i-call-a-sed-command-in-a-python-script) or [replace string in file with using regular expressions](https://stackoverflow.com/questions/35688126/replace-string-in-file-with-using-regular-expressions) or [How to search and replace text in a file?](https://stackoverflow.com/questions/17140886/how-to-search-and-replace-text-in-a-file) – NewPythonUser Jun 09 '20 at 10:36
  • yes, that works @NewPythonUser -- although I'll have to go back and use regex more directly. – Nicholas Saunders Jun 09 '20 at 10:47

2 Answers2

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]$ 
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.
Gustav Rasmussen
  • 3,720
  • 4
  • 23
  • 53