(gulp) newbie question - portablity of python

Andrew Dalke dalke at acm.org
Sun May 14 17:30:51 EDT 2000


Moshe Zadka wrote in message ...
>Keygrass wrote:
>> Basically, I want a build a program that will replace words and number on
>> another file.  For example, if I had a file called "Outdoor_sports" that
>> contained the word "baseball bat", I would want my program to change it
so
>> it would say "football".


Moshe Zadka wrote:
>Here it is, in its entirety.


>#!/usr/local/bin/python
>import string, sys
>
>def replace_word_in_file(file, word, replacement):
> f = open(file)
> s = f.read()
> f.close()
> s = string.replace(s, word, replacement)
> f = open(file, 'w')
> f.write(s)
> f.close()
>
>if __name__ == '__main__':
> if len(sys.argv) < 4:
>   exit(1)
> for file in sys.argv[3:]:
>   replace_word_in_file(sys.argv[1], sys.argv[2], file)


That won't replace "baseball bat" if it breaks across a newline.
You need do a regular expression replacement, converting " " to "\s+".
Something like the following, untested code.

import re, string
def replace_word_in_file(file, word, replacement):
  f = open(file)
  s = f.read()
  f.close()
  pattern = re.escape(word)
  pattern = string.replace(pattern, r'\ ', r'\s+')
  s = re.sub(pattern, replacement, s)
  f.open(file, "r")
  f.write(s)
  f.close()

>>> s = """This is a baseball
... bat from Cleveland."""
>>> word = "baseball bat"
>>> pattern = re.escape(word)
>>> print pattern
baseball\ bat
>>> pattern = string.replace(pattern, r'\ ', r'\s+')
>>> print pattern
baseball\s+bat
>>> re.sub(pattern, "football", s)
'This is a football from Cleveland.'
>>>

Even supports double spaced lines and form feeds :)

                    Andrew
                    dalke at acm.org






More information about the Python-list mailing list