I can't understand re.sub

Denis McMahon denismfmcmahon at gmail.com
Sun Nov 29 17:01:34 EST 2015


On 2015年11月29日 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 at gmail.com


More information about the Python-list mailing list

AltStyle によって変換されたページ (->オリジナル) /