Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #99702
| From | Denis McMahon <denismfmcmahon@gmail.com> |
|---|---|
| Newsgroups | comp.lang.python |
| Subject | Re: I can't understand re.sub |
| Date | 2015-11-29 22:01 +0000 |
| Organization | A noiseless patient Spider |
| Message-ID | <n3fsju$348$2@dont-email.me> (permalink) |
| References | <af27abe4-f81e-4d44-a504-c58d9e71986a@googlegroups.com> |
On Sun, 29 Nov 2015 13:36:57 -0800, Mr Zaug wrote:
> result = re.sub(pattern, repl, string, count=0, flags=0);
re.sub works on a string, not on a file.
Read the file to a string, pass it in as the string.
Or pre-compile the search pattern(s) and process the file line by line:
import re
patts = [
(re.compile("axe"), "hammer"),
(re.compile("cat"), "dog"),
(re.compile("tree"), "fence")
]
with open("input.txt","r") as inf, open("output.txt","w") as ouf:
line = inf.readline()
for patt in patts:
line = patt[0].sub(patt[1], line)
ouf.write(line)
Not tested, but I think it should do the trick.
Or use a single patt and a replacement func:
import re
patt = re.compile("(axe)|(cat)|(tree)")
def replfunc(match):
if match == 'axe':
return 'hammer'
if match == 'cat':
return 'dog'
if match == 'tree':
return 'fence'
return match
with open("input.txt","r") as inf, open("output.txt","w") as ouf:
line = inf.readline()
line = patt.sub(replfunc, line)
ouf.write(line)
(also not tested)
--
Denis McMahon, denismfmcmahon@gmail.com
Back to comp.lang.python | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread
I can't understand re.sub Mr Zaug <matthew.herzog@gmail.com> - 2015-11-29 13:36 -0800
Re: I can't understand re.sub Denis McMahon <denismfmcmahon@gmail.com> - 2015-11-29 22:01 +0000
Re: I can't understand re.sub Mr Zaug <matthew.herzog@gmail.com> - 2015-11-29 17:20 -0800
Re: I can't understand re.sub Rick Johnson <rantingrickjohnson@gmail.com> - 2015-11-29 17:12 -0800
Re: I can't understand re.sub Mr Zaug <matthew.herzog@gmail.com> - 2015-11-29 17:24 -0800
Re: I can't understand re.sub Erik <python@lucidity.plus.com> - 2015-11-29 21:53 +0000
Re: I can't understand re.sub Jussi Piitulainen <harvesting@is.invalid> - 2015-11-30 10:51 +0200
Re: I can't understand re.sub Erik <python@lucidity.plus.com> - 2015-12-01 01:26 +0000
Re: I can't understand re.sub Jussi Piitulainen <harvesting@is.invalid> - 2015-12-01 07:28 +0200
Re: I can't understand re.sub Erik <python@lucidity.plus.com> - 2015-12-01 21:31 +0000
csiph-web