PageRenderTime 46ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 1ms

/src/whoosh/analysis/intraword.py

https://bitbucket.org/rayleyva/whoosh
Python | 491 lines | 418 code | 16 blank | 57 comment | 20 complexity | 155f1b3b65f1162cea835acb35870bd9 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 re
  28. from collections import deque
  29. from whoosh.compat import u, text_type
  30. from whoosh.compat import xrange
  31. from whoosh.analysis.filters import Filter
  32. class CompoundWordFilter(Filter):
  33. """Given a set of words (or any object with a ``__contains__`` method),
  34. break any tokens in the stream that are composites of words in the word set
  35. into their individual parts.
  36. Given the correct set of words, this filter can break apart run-together
  37. words and trademarks (e.g. "turbosquid", "applescript"). It can also be
  38. useful for agglutinative languages such as German.
  39. The ``keep_compound`` argument lets you decide whether to keep the
  40. compound word in the token stream along with the word segments.
  41. >>> cwf = CompoundWordFilter(wordset, keep_compound=True)
  42. >>> analyzer = RegexTokenizer(r"\S+") | cwf
  43. >>> [t.text for t in analyzer("I do not like greeneggs and ham")
  44. ["I", "do", "not", "like", "greeneggs", "green", "eggs", "and", "ham"]
  45. >>> cwf.keep_compound = False
  46. >>> [t.text for t in analyzer("I do not like greeneggs and ham")
  47. ["I", "do", "not", "like", "green", "eggs", "and", "ham"]
  48. """
  49. def __init__(self, wordset, keep_compound=True):
  50. """
  51. :param wordset: an object with a ``__contains__`` method, such as a
  52. set, containing strings to look for inside the tokens.
  53. :param keep_compound: if True (the default), the original compound
  54. token will be retained in the stream before the subwords.
  55. """
  56. self.wordset = wordset
  57. self.keep_compound = keep_compound
  58. def subwords(self, s, memo):
  59. if s in self.wordset:
  60. return [s]
  61. if s in memo:
  62. return memo[s]
  63. for i in xrange(1, len(s)):
  64. prefix = s[:i]
  65. if prefix in self.wordset:
  66. suffix = s[i:]
  67. suffix_subs = self.subwords(suffix, memo)
  68. if suffix_subs:
  69. result = [prefix] + suffix_subs
  70. memo[s] = result
  71. return result
  72. return None
  73. def __call__(self, tokens):
  74. keep_compound = self.keep_compound
  75. memo = {}
  76. subwords = self.subwords
  77. for t in tokens:
  78. subs = subwords(t.text, memo)
  79. if subs:
  80. if len(subs) > 1 and keep_compound:
  81. yield t
  82. for subword in subs:
  83. t.text = subword
  84. yield t
  85. else:
  86. yield t
  87. class BiWordFilter(Filter):
  88. """Merges adjacent tokens into "bi-word" tokens, so that for example::
  89. "the", "sign", "of", "four"
  90. becomes::
  91. "the-sign", "sign-of", "of-four"
  92. This can be used to create fields for pseudo-phrase searching, where if
  93. all the terms match the document probably contains the phrase, but the
  94. searching is faster than actually doing a phrase search on individual word
  95. terms.
  96. The ``BiWordFilter`` is much faster than using the otherwise equivalent
  97. ``ShingleFilter(2)``.
  98. """
  99. def __init__(self, sep="-"):
  100. self.sep = sep
  101. def __call__(self, tokens):
  102. sep = self.sep
  103. prev_text = None
  104. prev_startchar = None
  105. prev_pos = None
  106. atleastone = False
  107. for token in tokens:
  108. # Save the original text of this token
  109. text = token.text
  110. # Save the original position
  111. positions = token.positions
  112. if positions:
  113. ps = token.pos
  114. # Save the original start char
  115. chars = token.chars
  116. if chars:
  117. sc = token.startchar
  118. if prev_text is not None:
  119. # Use the pos and startchar from the previous token
  120. if positions:
  121. token.pos = prev_pos
  122. if chars:
  123. token.startchar = prev_startchar
  124. # Join the previous token text and the current token text to
  125. # form the biword token
  126. token.text = "".join((prev_text, sep, text))
  127. yield token
  128. atleastone = True
  129. # Save the originals and the new "previous" values
  130. prev_text = text
  131. if chars:
  132. prev_startchar = sc
  133. if positions:
  134. prev_pos = ps
  135. # If no bi-words were emitted, that is, the token stream only had
  136. # a single token, then emit that single token.
  137. if not atleastone:
  138. yield token
  139. class ShingleFilter(Filter):
  140. """Merges a certain number of adjacent tokens into multi-word tokens, so
  141. that for example::
  142. "better", "a", "witty", "fool", "than", "a", "foolish", "wit"
  143. with ``ShingleFilter(3, ' ')`` becomes::
  144. 'better a witty', 'a witty fool', 'witty fool than', 'fool than a',
  145. 'than a foolish', 'a foolish wit'
  146. This can be used to create fields for pseudo-phrase searching, where if
  147. all the terms match the document probably contains the phrase, but the
  148. searching is faster than actually doing a phrase search on individual word
  149. terms.
  150. If you're using two-word shingles, you should use the functionally
  151. equivalent ``BiWordFilter`` instead because it's faster than
  152. ``ShingleFilter``.
  153. """
  154. def __init__(self, size=2, sep="-"):
  155. self.size = size
  156. self.sep = sep
  157. def __call__(self, tokens):
  158. size = self.size
  159. sep = self.sep
  160. buf = deque()
  161. atleastone = False
  162. def make_token():
  163. tk = buf[0]
  164. tk.text = sep.join([t.text for t in buf])
  165. if tk.chars:
  166. tk.endchar = buf[-1].endchar
  167. return tk
  168. for token in tokens:
  169. buf.append(token.copy())
  170. if len(buf) == size:
  171. atleastone = True
  172. yield make_token()
  173. buf.popleft()
  174. # If no shingles were emitted, that is, the token stream had fewer than
  175. # 'size' tokens, then emit a single token with whatever tokens there
  176. # were
  177. if not atleastone:
  178. yield make_token()
  179. class IntraWordFilter(Filter):
  180. """Splits words into subwords and performs optional transformations on
  181. subword groups. This filter is funtionally based on yonik's
  182. WordDelimiterFilter in Solr, but shares no code with it.
  183. * Split on intra-word delimiters, e.g. `Wi-Fi` -> `Wi`, `Fi`.
  184. * When splitwords=True, split on case transitions,
  185. e.g. `PowerShot` -> `Power`, `Shot`.
  186. * When splitnums=True, split on letter-number transitions,
  187. e.g. `SD500` -> `SD`, `500`.
  188. * Leading and trailing delimiter characters are ignored.
  189. * Trailing possesive "'s" removed from subwords,
  190. e.g. `O'Neil's` -> `O`, `Neil`.
  191. The mergewords and mergenums arguments turn on merging of subwords.
  192. When the merge arguments are false, subwords are not merged.
  193. * `PowerShot` -> `0`:`Power`, `1`:`Shot` (where `0` and `1` are token
  194. positions).
  195. When one or both of the merge arguments are true, consecutive runs of
  196. alphabetic and/or numeric subwords are merged into an additional token with
  197. the same position as the last sub-word.
  198. * `PowerShot` -> `0`:`Power`, `1`:`Shot`, `1`:`PowerShot`
  199. * `A's+B's&C's` -> `0`:`A`, `1`:`B`, `2`:`C`, `2`:`ABC`
  200. * `Super-Duper-XL500-42-AutoCoder!` -> `0`:`Super`, `1`:`Duper`, `2`:`XL`,
  201. `2`:`SuperDuperXL`,
  202. `3`:`500`, `4`:`42`, `4`:`50042`, `5`:`Auto`, `6`:`Coder`,
  203. `6`:`AutoCoder`
  204. When using this filter you should use a tokenizer that only splits on
  205. whitespace, so the tokenizer does not remove intra-word delimiters before
  206. this filter can see them, and put this filter before any use of
  207. LowercaseFilter.
  208. >>> rt = RegexTokenizer(r"\\S+")
  209. >>> iwf = IntraWordFilter()
  210. >>> lcf = LowercaseFilter()
  211. >>> analyzer = rt | iwf | lcf
  212. One use for this filter is to help match different written representations
  213. of a concept. For example, if the source text contained `wi-fi`, you
  214. probably want `wifi`, `WiFi`, `wi-fi`, etc. to match. One way of doing this
  215. is to specify mergewords=True and/or mergenums=True in the analyzer used
  216. for indexing, and mergewords=False / mergenums=False in the analyzer used
  217. for querying.
  218. >>> iwf_i = IntraWordFilter(mergewords=True, mergenums=True)
  219. >>> iwf_q = IntraWordFilter(mergewords=False, mergenums=False)
  220. >>> iwf = MultiFilter(index=iwf_i, query=iwf_q)
  221. >>> analyzer = RegexTokenizer(r"\S+") | iwf | LowercaseFilter()
  222. (See :class:`MultiFilter`.)
  223. """
  224. is_morph = True
  225. __inittypes__ = dict(delims=text_type, splitwords=bool, splitnums=bool,
  226. mergewords=bool, mergenums=bool)
  227. def __init__(self, delims=u("-_'\"()!@#$%^&*[]{}<>\|;:,./?`~=+"),
  228. splitwords=True, splitnums=True,
  229. mergewords=False, mergenums=False):
  230. """
  231. :param delims: a string of delimiter characters.
  232. :param splitwords: if True, split at case transitions,
  233. e.g. `PowerShot` -> `Power`, `Shot`
  234. :param splitnums: if True, split at letter-number transitions,
  235. e.g. `SD500` -> `SD`, `500`
  236. :param mergewords: merge consecutive runs of alphabetic subwords into
  237. an additional token with the same position as the last subword.
  238. :param mergenums: merge consecutive runs of numeric subwords into an
  239. additional token with the same position as the last subword.
  240. """
  241. from whoosh.support.unicode import digits, lowercase, uppercase
  242. self.delims = re.escape(delims)
  243. # Expression for text between delimiter characters
  244. self.between = re.compile(u("[^%s]+") % (self.delims,), re.UNICODE)
  245. # Expression for removing "'s" from the end of sub-words
  246. dispat = u("(?<=[%s%s])'[Ss](?=$|[%s])") % (lowercase, uppercase,
  247. self.delims)
  248. self.possessive = re.compile(dispat, re.UNICODE)
  249. # Expression for finding case and letter-number transitions
  250. lower2upper = u("[%s][%s]") % (lowercase, uppercase)
  251. letter2digit = u("[%s%s][%s]") % (lowercase, uppercase, digits)
  252. digit2letter = u("[%s][%s%s]") % (digits, lowercase, uppercase)
  253. if splitwords and splitnums:
  254. splitpat = u("(%s|%s|%s)") % (lower2upper, letter2digit,
  255. digit2letter)
  256. self.boundary = re.compile(splitpat, re.UNICODE)
  257. elif splitwords:
  258. self.boundary = re.compile(text_type(lower2upper), re.UNICODE)
  259. elif splitnums:
  260. numpat = u("(%s|%s)") % (letter2digit, digit2letter)
  261. self.boundary = re.compile(numpat, re.UNICODE)
  262. self.splitting = splitwords or splitnums
  263. self.mergewords = mergewords
  264. self.mergenums = mergenums
  265. def __eq__(self, other):
  266. return other and self.__class__ is other.__class__\
  267. and self.__dict__ == other.__dict__
  268. def _split(self, string):
  269. bound = self.boundary
  270. # Yields (startchar, endchar) pairs for each indexable substring in
  271. # the given string, e.g. "WikiWord" -> (0, 4), (4, 8)
  272. # Whether we're splitting on transitions (case changes, letter -> num,
  273. # num -> letter, etc.)
  274. splitting = self.splitting
  275. # Make a list (dispos, for "dispossessed") of (startchar, endchar)
  276. # pairs for runs of text between "'s"
  277. if "'" in string:
  278. # Split on possessive 's
  279. dispos = []
  280. prev = 0
  281. for match in self.possessive.finditer(string):
  282. dispos.append((prev, match.start()))
  283. prev = match.end()
  284. if prev < len(string):
  285. dispos.append((prev, len(string)))
  286. else:
  287. # Shortcut if there's no apostrophe in the string
  288. dispos = ((0, len(string)),)
  289. # For each run between 's
  290. for sc, ec in dispos:
  291. # Split on boundary characters
  292. for part_match in self.between.finditer(string, sc, ec):
  293. part_start = part_match.start()
  294. part_end = part_match.end()
  295. if splitting:
  296. # The point to start splitting at
  297. prev = part_start
  298. # Find transitions (e.g. "iW" or "a0")
  299. for bmatch in bound.finditer(string, part_start, part_end):
  300. # The point in the middle of the transition
  301. pivot = bmatch.start() + 1
  302. # Yield from the previous match to the transition
  303. yield (prev, pivot)
  304. # Make the transition the new starting point
  305. prev = pivot
  306. # If there's leftover text at the end, yield it too
  307. if prev < part_end:
  308. yield (prev, part_end)
  309. else:
  310. # Not splitting on transitions, just yield the part
  311. yield (part_start, part_end)
  312. def _merge(self, parts):
  313. mergewords = self.mergewords
  314. mergenums = self.mergenums
  315. # Current type (1=alpah, 2=digit)
  316. last = 0
  317. # Where to insert a merged term in the original list
  318. insertat = 0
  319. # Buffer for parts to merge
  320. buf = []
  321. # Iterate on a copy of the parts list so we can modify the original as
  322. # we go
  323. def insert_item(buf, at, newpos):
  324. newtext = "".join(item[0] for item in buf)
  325. newsc = buf[0][2] # start char of first item in buffer
  326. newec = buf[-1][3] # end char of last item in buffer
  327. parts.insert(insertat, (newtext, newpos, newsc, newec))
  328. for item in list(parts):
  329. # item = (text, pos, startchar, endchar)
  330. text = item[0]
  331. pos = item[1]
  332. # Set the type of this part
  333. if text.isalpha():
  334. this = 1
  335. elif text.isdigit():
  336. this = 2
  337. # Is this the same type as the previous part?
  338. if (buf and (this == last == 1 and mergewords)
  339. or (this == last == 2 and mergenums)):
  340. # This part is the same type as the previous. Add it to the
  341. # buffer of parts to merge.
  342. buf.append(item)
  343. else:
  344. # This part is different than the previous.
  345. if len(buf) > 1:
  346. # If the buffer has at least two parts in it, merge them
  347. # and add them to the original list of parts.
  348. insert_item(buf, insertat, pos - 1)
  349. insertat += 1
  350. # Reset the buffer
  351. buf = [item]
  352. last = this
  353. insertat += 1
  354. # If there are parts left in the buffer at the end, merge them and add
  355. # them to the original list.
  356. if len(buf) > 1:
  357. insert_item(buf, len(parts), pos)
  358. def __call__(self, tokens):
  359. mergewords = self.mergewords
  360. mergenums = self.mergenums
  361. # This filter renumbers tokens as it expands them. New position
  362. # counter.
  363. newpos = None
  364. for t in tokens:
  365. text = t.text
  366. # If this is the first token we've seen, use it to set the new
  367. # position counter
  368. if newpos is None:
  369. if t.positions:
  370. newpos = t.pos
  371. else:
  372. # Token doesn't have positions, just use 0
  373. newpos = 0
  374. if ((text.isalpha() and (text.islower() or text.isupper()))
  375. or text.isdigit()):
  376. # Short-circuit the common cases of no delimiters, no case
  377. # transitions, only digits, etc.
  378. t.pos = newpos
  379. yield t
  380. newpos += 1
  381. else:
  382. # Split the token text on delimiters, word and/or number
  383. # boundaries into a list of (text, pos, startchar, endchar)
  384. # tuples
  385. ranges = self._split(text)
  386. parts = [(text[sc:ec], i + newpos, sc, ec)
  387. for i, (sc, ec) in enumerate(ranges)]
  388. # Did the split yield more than one part?
  389. if len(parts) > 1:
  390. # If the options are set, merge consecutive runs of all-
  391. # letters and/or all-numbers.
  392. if mergewords or mergenums:
  393. self._merge(parts)
  394. # Yield tokens for the parts
  395. chars = t.chars
  396. if chars:
  397. base = t.startchar
  398. for text, pos, startchar, endchar in parts:
  399. t.text = text
  400. t.pos = pos
  401. if t.chars:
  402. t.startchar = base + startchar
  403. t.endchar = base + endchar
  404. yield t
  405. if parts:
  406. # Set the new position counter based on the last part
  407. newpos = parts[-1][1] + 1