PageRenderTime 116ms CodeModel.GetById 27ms RepoModel.GetById 0ms app.codeStats 0ms

/src/whoosh/util/text.py

https://bitbucket.org/rayleyva/whoosh
Python | 130 lines | 92 code | 8 blank | 30 comment | 0 complexity | 586a412ee2ed337e6e17f47fa6625f14 MD5 | raw file
Possible License(s): Apache-2.0
  1. # Copyright 2007 Matt Chaput. All rights reserved.
  2. #
  3. # Redistribution and use in source and binary forms, with or without
  4. # modification, are permitted provided that the following conditions are met:
  5. #
  6. # 1. Redistributions of source code must retain the above copyright notice,
  7. # this list of conditions and the following disclaimer.
  8. #
  9. # 2. Redistributions in binary form must reproduce the above copyright
  10. # notice, this list of conditions and the following disclaimer in the
  11. # documentation and/or other materials provided with the distribution.
  12. #
  13. # THIS SOFTWARE IS PROVIDED BY MATT CHAPUT ``AS IS'' AND ANY EXPRESS OR
  14. # IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
  15. # MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
  16. # EVENT SHALL MATT CHAPUT OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
  17. # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  18. # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
  19. # OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  20. # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  21. # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
  22. # EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  23. #
  24. # The views and conclusions contained in the software and documentation are
  25. # those of the authors and should not be interpreted as representing official
  26. # policies, either expressed or implied, of Matt Chaput.
  27. import codecs, re
  28. from whoosh.compat import string_type, u
  29. # Note: these functions return a tuple of (text, length), so when you call
  30. # them, you have to add [0] on the end, e.g. str = utf8encode(unicode)[0]
  31. utf8encode = codecs.getencoder("utf-8")
  32. utf8decode = codecs.getdecoder("utf-8")
  33. # Prefix encoding functions
  34. def first_diff(a, b):
  35. """Returns the position of the first differing character in the strings
  36. a and b. For example, first_diff('render', 'rending') == 4. This function
  37. limits the return value to 255 so the difference can be encoded in a single
  38. byte.
  39. """
  40. i = 0
  41. for i in xrange(0, len(a)):
  42. if a[i] != b[i] or i == 255:
  43. break
  44. return i
  45. def prefix_encode(a, b):
  46. """Compresses string b as an integer (encoded in a byte) representing
  47. the prefix it shares with a, followed by the suffix encoded as UTF-8.
  48. """
  49. i = first_diff(a, b)
  50. return chr(i) + b[i:].encode("utf-8")
  51. def prefix_encode_all(ls):
  52. """Compresses the given list of (unicode) strings by storing each string
  53. (except the first one) as an integer (encoded in a byte) representing
  54. the prefix it shares with its predecessor, followed by the suffix encoded
  55. as UTF-8.
  56. """
  57. last = u('')
  58. for w in ls:
  59. i = first_diff(last, w)
  60. yield chr(i) + w[i:].encode("utf-8")
  61. last = w
  62. def prefix_decode_all(ls):
  63. """Decompresses a list of strings compressed by prefix_encode().
  64. """
  65. last = u('')
  66. for w in ls:
  67. i = ord(w[0])
  68. decoded = last[:i] + w[1:].decode("utf-8")
  69. yield decoded
  70. last = decoded
  71. # Natural key sorting function
  72. _nkre = re.compile(r"\D+|\d+", re.UNICODE)
  73. def _nkconv(i):
  74. try:
  75. return int(i)
  76. except ValueError:
  77. return i.lower()
  78. def natural_key(s):
  79. """Converts string ``s`` into a tuple that will sort "naturally" (i.e.,
  80. ``name5`` will come before ``name10`` and ``1`` will come before ``A``).
  81. This function is designed to be used as the ``key`` argument to sorting
  82. functions.
  83. :param s: the str/unicode string to convert.
  84. :rtype: tuple
  85. """
  86. # Use _nkre to split the input string into a sequence of
  87. # digit runs and non-digit runs. Then use _nkconv() to convert
  88. # the digit runs into ints and the non-digit runs to lowercase.
  89. return tuple(_nkconv(m) for m in _nkre.findall(s))
  90. # Regular expression functions
  91. def rcompile(pattern, flags=0, verbose=False):
  92. """A wrapper for re.compile that checks whether "pattern" is a regex object
  93. or a string to be compiled, and automatically adds the re.UNICODE flag.
  94. """
  95. if not isinstance(pattern, string_type):
  96. # If it's not a string, assume it's already a compiled pattern
  97. return pattern
  98. if verbose:
  99. flags |= re.VERBOSE
  100. return re.compile(pattern, re.UNICODE | flags)