deduplicator.py 894 B

1234567891011121314151617181920212223242526272829
  1. import typing
  2. import re
  3. def dedupilicate(value: str, existing_values: typing.Iterable[str]):
  4. """
  5. If <value> is present in <existing_value>, returns '<value>(1)'. If '<value>(1)' is present in <existing_values>,
  6. returns '<value>(2)' and so on. A typical use would run <value> through this function and then append it to
  7. <existing_values>.
  8. :param value: str
  9. :param existing_values: an iterable of strings
  10. :return: str
  11. """
  12. reccurances = []
  13. for existing_label in existing_values:
  14. if value == existing_label:
  15. reccurances.append(1)
  16. re_match = re.match(f"{value}\((.*)\)", existing_label)
  17. if re_match:
  18. current_reccurance = int(re_match.group(1))
  19. reccurances.append(current_reccurance + 1)
  20. if len(reccurances) == 0:
  21. return value
  22. else:
  23. return f"{value}({max(reccurances)})"