A Python robot that edits Wikipedia and interacts with people over IRC https://en.wikipedia.org/wiki/User:EarwigBot
25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

149 lines
5.6 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. try:
  24. from bs4 import BeautifulSoup
  25. except ImportError:
  26. BeautifulSoup = None
  27. try:
  28. import mwparserfromhell
  29. except ImportError:
  30. mwparserfromhell = None
  31. try:
  32. import nltk
  33. except ImportError:
  34. nltk = None
  35. __all__ = ["BaseTextParser", "ArticleTextParser", "HTMLTextParser"]
  36. class BaseTextParser(object):
  37. """Base class for a parser that handles text."""
  38. def __init__(self, text):
  39. self.text = text
  40. def __repr__(self):
  41. """Return the canonical string representation of the text parser."""
  42. return "{0}(text={1!r})".format(self.__class__.__name__, self.text)
  43. def __str__(self):
  44. """Return a nice string representation of the text parser."""
  45. name = self.__class__.__name__
  46. return "<{0} of text with size {1}>".format(name, len(text))
  47. class ArticleTextParser(BaseTextParser):
  48. """A parser that can strip and chunk wikicode article text."""
  49. def strip(self):
  50. """Clean the page's raw text by removing templates and formatting.
  51. Return the page's text with all HTML and wikicode formatting removed,
  52. including templates, tables, and references. It retains punctuation
  53. (spacing, paragraphs, periods, commas, (semi)-colons, parentheses,
  54. quotes), original capitalization, and so forth. HTML entities are
  55. replaced by their unicode equivalents.
  56. The actual stripping is handled by :py:mod:`mwparserfromhell`.
  57. """
  58. wikicode = mwparserfromhell.parse(self.text)
  59. self.clean = wikicode.strip_code(normalize=True)
  60. return self.clean
  61. def chunk(self, nltk_dir, max_chunks, max_query=256):
  62. """Convert the clean article text into a list of web-searchable chunks.
  63. No greater than *max_chunks* will be returned. Each chunk will only be
  64. a sentence or two long at most (no more than *max_query*). The idea is
  65. to return a sample of the article text rather than the whole, so we'll
  66. pick and choose from parts of it, especially if the article is large
  67. and *max_chunks* is low, so we don't end up just searching for just the
  68. first paragraph.
  69. This is implemented using :py:mod:`nltk` (http://nltk.org/). A base
  70. directory (*nltk_dir*) is required to store nltk's punctuation
  71. database. This is typically located in the bot's working directory.
  72. """
  73. datafile = path.join(nltk_dir, "tokenizers", "punkt", "english.pickle")
  74. try:
  75. tokenizer = nltk.data.load("file:" + datafile)
  76. except LookupError:
  77. nltk.download("punkt", nltk_dir)
  78. tokenizer = nltk.data.load("file:" + datafile)
  79. sentences = []
  80. for sentence in tokenizer.tokenize(self.clean):
  81. if len(sentence) > max_query:
  82. words = sentence.split()
  83. while len(" ".join(words)) > max_query:
  84. words.pop()
  85. sentence = " ".join(words)
  86. sentences.append(sentence)
  87. if max_chunks >= len(sentences):
  88. return sentences
  89. chunks = []
  90. while len(chunks) < max_chunks:
  91. if len(chunks) % 5 == 0:
  92. chunk = sentences.pop(0) # Pop from beginning
  93. elif len(chunks) % 5 == 1:
  94. chunk = sentences.pop() # Pop from end
  95. elif len(chunks) % 5 == 2:
  96. chunk = sentences.pop(len(sentences) / 2) # Pop from Q2
  97. elif len(chunks) % 5 == 3:
  98. chunk = sentences.pop(len(sentences) / 4) # Pop from Q1
  99. else:
  100. chunk = sentences.pop(3 * len(sentences) / 4) # Pop from Q3
  101. chunks.append(chunk)
  102. return chunks
  103. class HTMLTextParser(BaseTextParser):
  104. """A parser that can extract the text from an HTML document."""
  105. hidden_tags = [
  106. "script", "style"
  107. ]
  108. def strip(self):
  109. """Return the actual text contained within an HTML document.
  110. Implemented using :py:mod:`BeautifulSoup <bs4>`
  111. (http://www.crummy.com/software/BeautifulSoup/).
  112. """
  113. try:
  114. soup = BeautifulSoup(self.text, "lxml").body
  115. except ValueError:
  116. soup = BeautifulSoup(self.text).body
  117. is_comment = lambda text: isinstance(text, bs4.element.Comment)
  118. [comment.extract() for comment in soup.find_all(text=is_comment)]
  119. for tag in self.hidden_tags:
  120. [element.extract() for element in soup.find_all(tag)]
  121. return "\n".join(soup.stripped_strings)