replace-word-pairs.py 778 B

1234567891011121314151617181920212223242526272829
  1. import sys
  2. import re
  3. # Reads from stdin line by line, writes to stdout line by line replacing
  4. # each odd argument with the subsequent even argument.
  5. def pairs(it):
  6. it = iter(it)
  7. try:
  8. while True:
  9. yield next(it), next(it)
  10. except StopIteration:
  11. return
  12. def main():
  13. rep_dict = dict()
  14. for fro, to in pairs(sys.argv[1:]):
  15. rep_dict[fro] = to
  16. if len(rep_dict):
  17. regex = re.compile("(%s)" % "|".join(map(re.escape, rep_dict.keys())))
  18. for line in iter(sys.stdin.readline, ''):
  19. sys.stdout.write(regex.sub(lambda mo: rep_dict[mo.string[mo.start():mo.end()]], line))
  20. else:
  21. for line in iter(sys.stdin.readline, ''):
  22. sys.stdout.write(line)
  23. if __name__ == '__main__':
  24. main()