A Python robot that edits Wikipedia and interacts with people over IRC https://en.wikipedia.org/wiki/User:EarwigBot
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

139 lines
5.5 KiB

  1. # -*- coding: utf-8 -*-
  2. #
  3. # Copyright (C) 2009-2012 Ben Kurtovic <ben.kurtovic@verizon.net>
  4. #
  5. # Permission is hereby granted, free of charge, to any person obtaining a copy
  6. # of this software and associated documentation files (the "Software"), to deal
  7. # in the Software without restriction, including without limitation the rights
  8. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. # copies of the Software, and to permit persons to whom the Software is
  10. # furnished to do so, subject to the following conditions:
  11. #
  12. # The above copyright notice and this permission notice shall be included in
  13. # all copies or substantial portions of the Software.
  14. #
  15. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  21. # SOFTWARE.
  22. from os import path
  23. import bs4
  24. import mwparserfromhell
  25. import nltk
  26. __all__ = ["BaseTextParser", "ArticleTextParser", "HTMLTextParser"]
  27. class BaseTextParser(object):
  28. """Base class for a parser that handles text."""
  29. def __init__(self, text):
  30. self.text = text
  31. def __repr__(self):
  32. """Return the canonical string representation of the text parser."""
  33. return "{0}(text={1!r})".format(self.__class__.__name__, self.text)
  34. def __str__(self):
  35. """Return a nice string representation of the text parser."""
  36. name = self.__class__.__name__
  37. return "<{0} of text with size {1}>".format(name, len(self.text))
  38. class ArticleTextParser(BaseTextParser):
  39. """A parser that can strip and chunk wikicode article text."""
  40. def strip(self):
  41. """Clean the page's raw text by removing templates and formatting.
  42. Return the page's text with all HTML and wikicode formatting removed,
  43. including templates, tables, and references. It retains punctuation
  44. (spacing, paragraphs, periods, commas, (semi)-colons, parentheses,
  45. quotes), original capitalization, and so forth. HTML entities are
  46. replaced by their unicode equivalents.
  47. The actual stripping is handled by :py:mod:`mwparserfromhell`.
  48. """
  49. wikicode = mwparserfromhell.parse(self.text)
  50. clean = wikicode.strip_code(normalize=True, collapse=True)
  51. self.clean = clean.replace("\n\n", "\n") # Collapse extra newlines
  52. return self.clean
  53. def chunk(self, nltk_dir, max_chunks, max_query=256):
  54. """Convert the clean article text into a list of web-searchable chunks.
  55. No greater than *max_chunks* will be returned. Each chunk will only be
  56. a sentence or two long at most (no more than *max_query*). The idea is
  57. to return a sample of the article text rather than the whole, so we'll
  58. pick and choose from parts of it, especially if the article is large
  59. and *max_chunks* is low, so we don't end up just searching for just the
  60. first paragraph.
  61. This is implemented using :py:mod:`nltk` (http://nltk.org/). A base
  62. directory (*nltk_dir*) is required to store nltk's punctuation
  63. database. This is typically located in the bot's working directory.
  64. """
  65. datafile = path.join(nltk_dir, "tokenizers", "punkt", "english.pickle")
  66. try:
  67. tokenizer = nltk.data.load("file:" + datafile)
  68. except LookupError:
  69. nltk.download("punkt", nltk_dir)
  70. tokenizer = nltk.data.load("file:" + datafile)
  71. sentences = []
  72. for sentence in tokenizer.tokenize(self.clean):
  73. if len(sentence) > max_query:
  74. words = sentence.split()
  75. while len(" ".join(words)) > max_query:
  76. words.pop()
  77. sentence = " ".join(words)
  78. sentences.append(sentence)
  79. if max_chunks >= len(sentences):
  80. return sentences
  81. chunks = []
  82. while len(chunks) < max_chunks:
  83. if len(chunks) % 5 == 0:
  84. chunk = sentences.pop(0) # Pop from beginning
  85. elif len(chunks) % 5 == 1:
  86. chunk = sentences.pop() # Pop from end
  87. elif len(chunks) % 5 == 2:
  88. chunk = sentences.pop(len(sentences) / 2) # Pop from Q2
  89. elif len(chunks) % 5 == 3:
  90. chunk = sentences.pop(len(sentences) / 4) # Pop from Q1
  91. else:
  92. chunk = sentences.pop(3 * len(sentences) / 4) # Pop from Q3
  93. chunks.append(chunk)
  94. return chunks
  95. class HTMLTextParser(BaseTextParser):
  96. """A parser that can extract the text from an HTML document."""
  97. hidden_tags = [
  98. "script", "style"
  99. ]
  100. def strip(self):
  101. """Return the actual text contained within an HTML document.
  102. Implemented using :py:mod:`BeautifulSoup <bs4>`
  103. (http://www.crummy.com/software/BeautifulSoup/).
  104. """
  105. try:
  106. soup = bs4.BeautifulSoup(self.text, "lxml").body
  107. except ValueError:
  108. soup = bs4.BeautifulSoup(self.text).body
  109. is_comment = lambda text: isinstance(text, bs4.element.Comment)
  110. [comment.extract() for comment in soup.find_all(text=is_comment)]
  111. for tag in self.hidden_tags:
  112. [element.extract() for element in soup.find_all(tag)]
  113. return "\n".join(soup.stripped_strings)