text.py 27 KB

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