hiermatch.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. # hiermatch - Doing match on a list of string or a hierarchy.
  2. # Written by Chris Lawrence <lawrencc@debian.org>
  3. # Copyright (C) 1999-2008 Chris Lawrence
  4. # Copyright (C) 2008-2016 Sandro Tosi <morph@debian.org>
  5. import re
  6. import exceptions
  7. def egrep_list(strlist, pattern_str, subindex=None):
  8. """Use the pattern_str to find any match in a list of strings."""
  9. """Return: a list of index for the matchs into the origin list."""
  10. if strlist is None:
  11. return None
  12. try:
  13. pat = re.compile(pattern_str, re.I | re.M)
  14. except:
  15. raise exceptions.InvalidRegex
  16. resultlist = []
  17. if subindex is None:
  18. subindex = range(len(strlist))
  19. for i in subindex:
  20. if pat.search(strlist[i]):
  21. resultlist.append(i)
  22. return resultlist
  23. def egrep_hierarchy(hier, pattern_str, subhier=None, nth=1):
  24. """Grep the nth item of a hierarchy [(x, [a, b]),...]."""
  25. """Return a subhier like [[n, m],[],...], n, m string index."""
  26. resulthier = []
  27. for i in range(len(hier)):
  28. if subhier:
  29. if subhier[i]: # Only if have something to match.
  30. resultlist = egrep_list(hier[i][nth], pattern_str, subhier[i])
  31. else:
  32. resultlist = []
  33. else:
  34. resultlist = egrep_list(hier[i][nth], pattern_str)
  35. resulthier.append(resultlist)
  36. return resulthier
  37. def matched_hierarchy(hier, pattern_str):
  38. """Actually create a new hierarchy from a pattern matching."""
  39. mhier = []
  40. result = egrep_hierarchy(hier, pattern_str)
  41. for i in range(len(result)):
  42. if result[i]:
  43. item = [hier[i][1][y] for y in result[i]]
  44. mhier.append((hier[i][0], item))
  45. return mhier
  46. # vim:ts=8:sw=4:expandtab: