Advertisement
homer512

subxy

May 11th, 2014
320
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.92 KB | None | 0 0
  1. #!/usr/bin/python2
  2.  
  3. # Copyright 2014 Florian Philipp
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. #    http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16.  
  17. import re
  18.  
  19. def subxy(string, originals, replacements, flags = 0):
  20.     """Replaces all occurrences of originals in string with replacements
  21.  
  22.    Each original will be replaced with the replacement of the same index
  23.  
  24.    Arguments:
  25.    string -- str or unicode to search and replace
  26.    originals -- iterable of strings to search for
  27.    replacements -- sequence of strings to replace originals. Has to have the
  28.                    same length as originals
  29.    flags -- regex flags. See re.compile. Only re.IGNORECASE is of real
  30.             interest at the moment
  31.    """
  32.     escaped = [re.escape(orig) for orig in originals]
  33.     inner_pattern = str.join(')|(', escaped)
  34.     pattern = str.join('', ('(', inner_pattern, ')'))
  35.     regex = re.compile(pattern, flags)
  36.     def pick_replace(match):
  37.         """Identifies the first matching group and selects that replacement"""
  38.         groups = match.groups()
  39.         nonempty = [index for index, group in enumerate(groups)
  40.                     if group is not None]
  41.         return replacements[nonempty[0]]
  42.     return re.sub(regex, pick_replace, string)
  43.    
  44.  
  45. def main():
  46.     test_string = 'Foo bar baz quz bar'
  47.     origs = ('bar', 'quz')
  48.     repls = ('BAR', 'QUZ')
  49.     replaced = subxy(test_string, origs, repls)
  50.     print replaced
  51.  
  52. if __name__ == '__main__':
  53.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement