PageRenderTime 56ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 0ms

/nltk/text.py

https://github.com/BrucePHill/nltk
Python | 626 lines | 488 code | 33 blank | 105 comment | 33 complexity | 8da7552690478f4d3aab502136ab5373 MD5 | raw file
Possible License(s): Apache-2.0
  1. # Natural Language Toolkit: Texts
  2. #
  3. # Copyright (C) 2001-2013 NLTK Project
  4. # Author: Steven Bird <stevenbird1@gmail.com>
  5. # Edward Loper <edloper@gradient.cis.upenn.edu>
  6. # URL: <http://www.nltk.org/>
  7. # For license information, see LICENSE.TXT
  8. """
  9. This module brings together a variety of NLTK functionality for
  10. text analysis, and provides simple, interactive interfaces.
  11. Functionality includes: concordancing, collocation discovery,
  12. regular expression search over tokenized strings, and
  13. distributional similarity.
  14. """
  15. from __future__ import print_function, division, unicode_literals
  16. from math import log
  17. from collections import defaultdict
  18. from functools import reduce
  19. from itertools import islice
  20. import re
  21. from nltk.probability import FreqDist, LidstoneProbDist
  22. from nltk.probability import ConditionalFreqDist as CFD
  23. from nltk.util import tokenwrap, LazyConcatenation
  24. from nltk.model import NgramModel
  25. from nltk.metrics import f_measure, BigramAssocMeasures
  26. from nltk.collocations import BigramCollocationFinder
  27. from nltk.compat import python_2_unicode_compatible, text_type
  28. class ContextIndex(object):
  29. """
  30. A bidirectional index between words and their 'contexts' in a text.
  31. The context of a word is usually defined to be the words that occur
  32. in a fixed window around the word; but other definitions may also
  33. be used by providing a custom context function.
  34. """
  35. @staticmethod
  36. def _default_context(tokens, i):
  37. """One left token and one right token, normalized to lowercase"""
  38. left = (tokens[i-1].lower() if i != 0 else '*START*')
  39. right = (tokens[i+1].lower() if i != len(tokens) - 1 else '*END*')
  40. return (left, right)
  41. def __init__(self, tokens, context_func=None, filter=None, key=lambda x:x):
  42. self._key = key
  43. self._tokens = tokens
  44. if context_func:
  45. self._context_func = context_func
  46. else:
  47. self._context_func = self._default_context
  48. if filter:
  49. tokens = [t for t in tokens if filter(t)]
  50. self._word_to_contexts = CFD((self._key(w), self._context_func(tokens, i))
  51. for i, w in enumerate(tokens))
  52. self._context_to_words = CFD((self._context_func(tokens, i), self._key(w))
  53. for i, w in enumerate(tokens))
  54. def tokens(self):
  55. """
  56. :rtype: list(str)
  57. :return: The document that this context index was
  58. created from.
  59. """
  60. return self._tokens
  61. def word_similarity_dict(self, word):
  62. """
  63. Return a dictionary mapping from words to 'similarity scores,'
  64. indicating how often these two words occur in the same
  65. context.
  66. """
  67. word = self._key(word)
  68. word_contexts = set(self._word_to_contexts[word])
  69. scores = {}
  70. for w, w_contexts in self._word_to_contexts.items():
  71. scores[w] = f_measure(word_contexts, set(w_contexts))
  72. return scores
  73. def similar_words(self, word, n=20):
  74. scores = defaultdict(int)
  75. for c in self._word_to_contexts[self._key(word)]:
  76. for w in self._context_to_words[c]:
  77. if w != word:
  78. scores[w] += self._context_to_words[c][word] * self._context_to_words[c][w]
  79. return sorted(scores, key=scores.get, reverse=True)[:n]
  80. def common_contexts(self, words, fail_on_unknown=False):
  81. """
  82. Find contexts where the specified words can all appear; and
  83. return a frequency distribution mapping each context to the
  84. number of times that context was used.
  85. :param words: The words used to seed the similarity search
  86. :type words: str
  87. :param fail_on_unknown: If true, then raise a value error if
  88. any of the given words do not occur at all in the index.
  89. """
  90. words = [self._key(w) for w in words]
  91. contexts = [set(self._word_to_contexts[w]) for w in words]
  92. empty = [words[i] for i in range(len(words)) if not contexts[i]]
  93. common = reduce(set.intersection, contexts)
  94. if empty and fail_on_unknown:
  95. raise ValueError("The following word(s) were not found:",
  96. " ".join(words))
  97. elif not common:
  98. # nothing in common -- just return an empty freqdist.
  99. return FreqDist()
  100. else:
  101. fd = FreqDist(c for w in words
  102. for c in self._word_to_contexts[w]
  103. if c in common)
  104. return fd
  105. @python_2_unicode_compatible
  106. class ConcordanceIndex(object):
  107. """
  108. An index that can be used to look up the offset locations at which
  109. a given word occurs in a document.
  110. """
  111. def __init__(self, tokens, key=lambda x:x):
  112. """
  113. Construct a new concordance index.
  114. :param tokens: The document (list of tokens) that this
  115. concordance index was created from. This list can be used
  116. to access the context of a given word occurrence.
  117. :param key: A function that maps each token to a normalized
  118. version that will be used as a key in the index. E.g., if
  119. you use ``key=lambda s:s.lower()``, then the index will be
  120. case-insensitive.
  121. """
  122. self._tokens = tokens
  123. """The document (list of tokens) that this concordance index
  124. was created from."""
  125. self._key = key
  126. """Function mapping each token to an index key (or None)."""
  127. self._offsets = defaultdict(list)
  128. """Dictionary mapping words (or keys) to lists of offset
  129. indices."""
  130. # Initialize the index (self._offsets)
  131. for index, word in enumerate(tokens):
  132. word = self._key(word)
  133. self._offsets[word].append(index)
  134. def tokens(self):
  135. """
  136. :rtype: list(str)
  137. :return: The document that this concordance index was
  138. created from.
  139. """
  140. return self._tokens
  141. def offsets(self, word):
  142. """
  143. :rtype: list(int)
  144. :return: A list of the offset positions at which the given
  145. word occurs. If a key function was specified for the
  146. index, then given word's key will be looked up.
  147. """
  148. word = self._key(word)
  149. return self._offsets[word]
  150. def __repr__(self):
  151. return '<ConcordanceIndex for %d tokens (%d types)>' % (
  152. len(self._tokens), len(self._offsets))
  153. def print_concordance(self, word, width=75, lines=25):
  154. """
  155. Print a concordance for ``word`` with the specified context window.
  156. :param word: The target word
  157. :type word: str
  158. :param width: The width of each line, in characters (default=80)
  159. :type width: int
  160. :param lines: The number of lines to display (default=25)
  161. :type lines: int
  162. """
  163. half_width = (width - len(word) - 2) // 2
  164. context = width // 4 # approx number of words of context
  165. offsets = self.offsets(word)
  166. if offsets:
  167. lines = min(lines, len(offsets))
  168. print("Displaying %s of %s matches:" % (lines, len(offsets)))
  169. for i in offsets:
  170. if lines <= 0:
  171. break
  172. left = (' ' * half_width +
  173. ' '.join(self._tokens[i-context:i]))
  174. right = ' '.join(self._tokens[i+1:i+context])
  175. left = left[-half_width:]
  176. right = right[:half_width]
  177. print(left, self._tokens[i], right)
  178. lines -= 1
  179. else:
  180. print("No matches")
  181. class TokenSearcher(object):
  182. """
  183. A class that makes it easier to use regular expressions to search
  184. over tokenized strings. The tokenized string is converted to a
  185. string where tokens are marked with angle brackets -- e.g.,
  186. ``'<the><window><is><still><open>'``. The regular expression
  187. passed to the ``findall()`` method is modified to treat angle
  188. brackets as nongrouping parentheses, in addition to matching the
  189. token boundaries; and to have ``'.'`` not match the angle brackets.
  190. """
  191. def __init__(self, tokens):
  192. self._raw = ''.join('<'+w+'>' for w in tokens)
  193. def findall(self, regexp):
  194. """
  195. Find instances of the regular expression in the text.
  196. The text is a list of tokens, and a regexp pattern to match
  197. a single token must be surrounded by angle brackets. E.g.
  198. >>> from nltk.text import TokenSearcher
  199. >>> print('hack'); from nltk.book import text1, text5, text9
  200. hack...
  201. >>> text5.findall("<.*><.*><bro>")
  202. you rule bro; telling you bro; u twizted bro
  203. >>> text1.findall("<a>(<.*>)<man>")
  204. monied; nervous; dangerous; white; white; white; pious; queer; good;
  205. mature; white; Cape; great; wise; wise; butterless; white; fiendish;
  206. pale; furious; better; certain; complete; dismasted; younger; brave;
  207. brave; brave; brave
  208. >>> text9.findall("<th.*>{3,}")
  209. thread through those; the thought that; that the thing; the thing
  210. that; that that thing; through these than through; them that the;
  211. through the thick; them that they; thought that the
  212. :param regexp: A regular expression
  213. :type regexp: str
  214. """
  215. # preprocess the regular expression
  216. regexp = re.sub(r'\s', '', regexp)
  217. regexp = re.sub(r'<', '(?:<(?:', regexp)
  218. regexp = re.sub(r'>', ')>)', regexp)
  219. regexp = re.sub(r'(?<!\\)\.', '[^>]', regexp)
  220. # perform the search
  221. hits = re.findall(regexp, self._raw)
  222. # Sanity check
  223. for h in hits:
  224. if not h.startswith('<') and h.endswith('>'):
  225. raise ValueError('Bad regexp for TokenSearcher.findall')
  226. # postprocess the output
  227. hits = [h[1:-1].split('><') for h in hits]
  228. return hits
  229. @python_2_unicode_compatible
  230. class Text(object):
  231. """
  232. A wrapper around a sequence of simple (string) tokens, which is
  233. intended to support initial exploration of texts (via the
  234. interactive console). Its methods perform a variety of analyses
  235. on the text's contexts (e.g., counting, concordancing, collocation
  236. discovery), and display the results. If you wish to write a
  237. program which makes use of these analyses, then you should bypass
  238. the ``Text`` class, and use the appropriate analysis function or
  239. class directly instead.
  240. A ``Text`` is typically initialized from a given document or
  241. corpus. E.g.:
  242. >>> import nltk.corpus
  243. >>> from nltk.text import Text
  244. >>> moby = Text(nltk.corpus.gutenberg.words('melville-moby_dick.txt'))
  245. """
  246. # This defeats lazy loading, but makes things faster. This
  247. # *shouldn't* be necessary because the corpus view *should* be
  248. # doing intelligent caching, but without this it's running slow.
  249. # Look into whether the caching is working correctly.
  250. _COPY_TOKENS = True
  251. def __init__(self, tokens, name=None):
  252. """
  253. Create a Text object.
  254. :param tokens: The source text.
  255. :type tokens: sequence of str
  256. """
  257. if self._COPY_TOKENS:
  258. tokens = list(tokens)
  259. self.tokens = tokens
  260. if name:
  261. self.name = name
  262. elif ']' in tokens[:20]:
  263. end = tokens[:20].index(']')
  264. self.name = " ".join(text_type(tok) for tok in tokens[1:end])
  265. else:
  266. self.name = " ".join(text_type(tok) for tok in tokens[:8]) + "..."
  267. #////////////////////////////////////////////////////////////
  268. # Support item & slice access
  269. #////////////////////////////////////////////////////////////
  270. def __getitem__(self, i):
  271. if isinstance(i, slice):
  272. return self.tokens[i.start:i.stop]
  273. else:
  274. return self.tokens[i]
  275. def __len__(self):
  276. return len(self.tokens)
  277. #////////////////////////////////////////////////////////////
  278. # Interactive console methods
  279. #////////////////////////////////////////////////////////////
  280. def concordance(self, word, width=79, lines=25):
  281. """
  282. Print a concordance for ``word`` with the specified context window.
  283. Word matching is not case-sensitive.
  284. :seealso: ``ConcordanceIndex``
  285. """
  286. if '_concordance_index' not in self.__dict__:
  287. print("Building index...")
  288. self._concordance_index = ConcordanceIndex(self.tokens,
  289. key=lambda s:s.lower())
  290. self._concordance_index.print_concordance(word, width, lines)
  291. def collocations(self, num=20, window_size=2):
  292. """
  293. Print collocations derived from the text, ignoring stopwords.
  294. :seealso: find_collocations
  295. :param num: The maximum number of collocations to print.
  296. :type num: int
  297. :param window_size: The number of tokens spanned by a collocation (default=2)
  298. :type window_size: int
  299. """
  300. if not ('_collocations' in self.__dict__ and self._num == num and self._window_size == window_size):
  301. self._num = num
  302. self._window_size = window_size
  303. print("Building collocations list")
  304. from nltk.corpus import stopwords
  305. ignored_words = stopwords.words('english')
  306. finder = BigramCollocationFinder.from_words(self.tokens, window_size)
  307. finder.apply_freq_filter(2)
  308. finder.apply_word_filter(lambda w: len(w) < 3 or w.lower() in ignored_words)
  309. bigram_measures = BigramAssocMeasures()
  310. self._collocations = finder.nbest(bigram_measures.likelihood_ratio, num)
  311. colloc_strings = [w1+' '+w2 for w1, w2 in self._collocations]
  312. print(tokenwrap(colloc_strings, separator="; "))
  313. def count(self, word):
  314. """
  315. Count the number of times this word appears in the text.
  316. """
  317. return self.tokens.count(word)
  318. def index(self, word):
  319. """
  320. Find the index of the first occurrence of the word in the text.
  321. """
  322. return self.tokens.index(word)
  323. def readability(self, method):
  324. # code from nltk_contrib.readability
  325. raise NotImplementedError
  326. def generate(self, length=100):
  327. """
  328. Print random text, generated using a trigram language model.
  329. :param length: The length of text to generate (default=100)
  330. :type length: int
  331. :seealso: NgramModel
  332. """
  333. if '_trigram_model' not in self.__dict__:
  334. print("Building ngram index...")
  335. estimator = lambda fdist, bins: LidstoneProbDist(fdist, 0.2)
  336. self._trigram_model = NgramModel(3, self, estimator=estimator)
  337. text = self._trigram_model.generate(length)
  338. print(tokenwrap(text))
  339. def similar(self, word, num=20):
  340. """
  341. Distributional similarity: find other words which appear in the
  342. same contexts as the specified word; list most similar words first.
  343. :param word: The word used to seed the similarity search
  344. :type word: str
  345. :param num: The number of words to generate (default=20)
  346. :type num: int
  347. :seealso: ContextIndex.similar_words()
  348. """
  349. if '_word_context_index' not in self.__dict__:
  350. print('Building word-context index...')
  351. self._word_context_index = ContextIndex(self.tokens,
  352. filter=lambda x:x.isalpha(),
  353. key=lambda s:s.lower())
  354. # words = self._word_context_index.similar_words(word, num)
  355. word = word.lower()
  356. wci = self._word_context_index._word_to_contexts
  357. if word in wci.conditions():
  358. contexts = set(wci[word])
  359. fd = FreqDist(w for w in wci.conditions() for c in wci[w]
  360. if c in contexts and not w == word)
  361. words = islice(fd.keys(), num)
  362. print(tokenwrap(words))
  363. else:
  364. print("No matches")
  365. def common_contexts(self, words, num=20):
  366. """
  367. Find contexts where the specified words appear; list
  368. most frequent common contexts first.
  369. :param word: The word used to seed the similarity search
  370. :type word: str
  371. :param num: The number of words to generate (default=20)
  372. :type num: int
  373. :seealso: ContextIndex.common_contexts()
  374. """
  375. if '_word_context_index' not in self.__dict__:
  376. print('Building word-context index...')
  377. self._word_context_index = ContextIndex(self.tokens,
  378. key=lambda s:s.lower())
  379. try:
  380. fd = self._word_context_index.common_contexts(words, True)
  381. if not fd:
  382. print("No common contexts were found")
  383. else:
  384. ranked_contexts = islice(fd.keys(), num)
  385. print(tokenwrap(w1+"_"+w2 for w1,w2 in ranked_contexts))
  386. except ValueError as e:
  387. print(e)
  388. def dispersion_plot(self, words):
  389. """
  390. Produce a plot showing the distribution of the words through the text.
  391. Requires pylab to be installed.
  392. :param words: The words to be plotted
  393. :type word: str
  394. :seealso: nltk.draw.dispersion_plot()
  395. """
  396. from nltk.draw import dispersion_plot
  397. dispersion_plot(self, words)
  398. def plot(self, *args):
  399. """
  400. See documentation for FreqDist.plot()
  401. :seealso: nltk.prob.FreqDist.plot()
  402. """
  403. self.vocab().plot(*args)
  404. def vocab(self):
  405. """
  406. :seealso: nltk.prob.FreqDist
  407. """
  408. if "_vocab" not in self.__dict__:
  409. print("Building vocabulary index...")
  410. self._vocab = FreqDist(self)
  411. return self._vocab
  412. def findall(self, regexp):
  413. """
  414. Find instances of the regular expression in the text.
  415. The text is a list of tokens, and a regexp pattern to match
  416. a single token must be surrounded by angle brackets. E.g.
  417. >>> print('hack'); from nltk.book import text1, text5, text9
  418. hack...
  419. >>> text5.findall("<.*><.*><bro>")
  420. you rule bro; telling you bro; u twizted bro
  421. >>> text1.findall("<a>(<.*>)<man>")
  422. monied; nervous; dangerous; white; white; white; pious; queer; good;
  423. mature; white; Cape; great; wise; wise; butterless; white; fiendish;
  424. pale; furious; better; certain; complete; dismasted; younger; brave;
  425. brave; brave; brave
  426. >>> text9.findall("<th.*>{3,}")
  427. thread through those; the thought that; that the thing; the thing
  428. that; that that thing; through these than through; them that the;
  429. through the thick; them that they; thought that the
  430. :param regexp: A regular expression
  431. :type regexp: str
  432. """
  433. if "_token_searcher" not in self.__dict__:
  434. self._token_searcher = TokenSearcher(self)
  435. hits = self._token_searcher.findall(regexp)
  436. hits = [' '.join(h) for h in hits]
  437. print(tokenwrap(hits, "; "))
  438. #////////////////////////////////////////////////////////////
  439. # Helper Methods
  440. #////////////////////////////////////////////////////////////
  441. _CONTEXT_RE = re.compile('\w+|[\.\!\?]')
  442. def _context(self, tokens, i):
  443. """
  444. One left & one right token, both case-normalized. Skip over
  445. non-sentence-final punctuation. Used by the ``ContextIndex``
  446. that is created for ``similar()`` and ``common_contexts()``.
  447. """
  448. # Left context
  449. j = i-1
  450. while j>=0 and not self._CONTEXT_RE.match(tokens[j]):
  451. j -= 1
  452. left = (tokens[j] if j != 0 else '*START*')
  453. # Right context
  454. j = i+1
  455. while j<len(tokens) and not self._CONTEXT_RE.match(tokens[j]):
  456. j += 1
  457. right = (tokens[j] if j != len(tokens) else '*END*')
  458. return (left, right)
  459. #////////////////////////////////////////////////////////////
  460. # String Display
  461. #////////////////////////////////////////////////////////////
  462. def __str__(self):
  463. return '<Text: %s>' % self.name
  464. def __repr__(self):
  465. return '<Text: %s>' % self.name
  466. # Prototype only; this approach will be slow to load
  467. class TextCollection(Text):
  468. """A collection of texts, which can be loaded with list of texts, or
  469. with a corpus consisting of one or more texts, and which supports
  470. counting, concordancing, collocation discovery, etc. Initialize a
  471. TextCollection as follows:
  472. >>> import nltk.corpus
  473. >>> from nltk.text import TextCollection
  474. >>> print('hack'); from nltk.book import text1, text2, text3
  475. hack...
  476. >>> gutenberg = TextCollection(nltk.corpus.gutenberg)
  477. >>> mytexts = TextCollection([text1, text2, text3])
  478. Iterating over a TextCollection produces all the tokens of all the
  479. texts in order.
  480. """
  481. def __init__(self, source, name=None):
  482. if hasattr(source, 'words'): # bridge to the text corpus reader
  483. source = [source.words(f) for f in source.fileids()]
  484. self._texts = source
  485. Text.__init__(self, LazyConcatenation(source))
  486. self._idf_cache = {}
  487. def tf(self, term, text, method=None):
  488. """ The frequency of the term in text. """
  489. return text.count(term) / len(text)
  490. def idf(self, term, method=None):
  491. """ The number of texts in the corpus divided by the
  492. number of texts that the term appears in.
  493. If a term does not appear in the corpus, 0.0 is returned. """
  494. # idf values are cached for performance.
  495. idf = self._idf_cache.get(term)
  496. if idf is None:
  497. matches = len([True for text in self._texts if term in text])
  498. # FIXME Should this raise some kind of error instead?
  499. idf = (log(float(len(self._texts)) / matches) if matches else 0.0)
  500. self._idf_cache[term] = idf
  501. return idf
  502. def tf_idf(self, term, text):
  503. return self.tf(term, text) * self.idf(term)
  504. def demo():
  505. from nltk.corpus import brown
  506. text = Text(brown.words(categories='news'))
  507. print(text)
  508. print()
  509. print("Concordance:")
  510. text.concordance('news')
  511. print()
  512. print("Distributionally similar words:")
  513. text.similar('news')
  514. print()
  515. print("Collocations:")
  516. text.collocations()
  517. print()
  518. print("Automatically generated text:")
  519. text.generate()
  520. print()
  521. print("Dispersion plot:")
  522. text.dispersion_plot(['news', 'report', 'said', 'announced'])
  523. print()
  524. print("Vocabulary plot:")
  525. text.plot(50)
  526. print()
  527. print("Indexing:")
  528. print("text[3]:", text[3])
  529. print("text[3:5]:", text[3:5])
  530. print("text.vocab()['news']:", text.vocab()['news'])
  531. if __name__ == '__main__':
  532. demo()
  533. __all__ = ["ContextIndex",
  534. "ConcordanceIndex",
  535. "TokenSearcher",
  536. "Text",
  537. "TextCollection"]