jusText 4.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (110) hide show
  1. justext/__init__.py +15 -0
  2. justext/__main__.py +329 -0
  3. justext/_compat.py +53 -0
  4. justext/core.py +462 -0
  5. justext/paragraph.py +66 -0
  6. justext/stoplists/Afrikaans.txt +209 -0
  7. justext/stoplists/Albanian.txt +529 -0
  8. justext/stoplists/Arabic.txt +2762 -0
  9. justext/stoplists/Aragonese.txt +153 -0
  10. justext/stoplists/Armenian.txt +2908 -0
  11. justext/stoplists/Aromanian.txt +499 -0
  12. justext/stoplists/Asturian.txt +656 -0
  13. justext/stoplists/Azerbaijani.txt +3739 -0
  14. justext/stoplists/Basque.txt +2274 -0
  15. justext/stoplists/Belarusian.txt +4418 -0
  16. justext/stoplists/Belarusian_Taraskievica.txt +4098 -0
  17. justext/stoplists/Bengali.txt +1089 -0
  18. justext/stoplists/Bishnupriya_Manipuri.txt +55 -0
  19. justext/stoplists/Bosnian.txt +2234 -0
  20. justext/stoplists/Breton.txt +290 -0
  21. justext/stoplists/Bulgarian.txt +1134 -0
  22. justext/stoplists/Catalan.txt +227 -0
  23. justext/stoplists/Cebuano.txt +10 -0
  24. justext/stoplists/Chuvash.txt +2588 -0
  25. justext/stoplists/Croatian.txt +2463 -0
  26. justext/stoplists/Czech.txt +3208 -0
  27. justext/stoplists/Danish.txt +559 -0
  28. justext/stoplists/Dutch.txt +290 -0
  29. justext/stoplists/English.txt +503 -0
  30. justext/stoplists/Esperanto.txt +564 -0
  31. justext/stoplists/Estonian.txt +6295 -0
  32. justext/stoplists/Finnish.txt +7317 -0
  33. justext/stoplists/French.txt +414 -0
  34. justext/stoplists/Galician.txt +449 -0
  35. justext/stoplists/Georgian.txt +5433 -0
  36. justext/stoplists/German.txt +692 -0
  37. justext/stoplists/Greek.txt +626 -0
  38. justext/stoplists/Gujarati.txt +404 -0
  39. justext/stoplists/Haitian.txt +33 -0
  40. justext/stoplists/Hebrew.txt +4270 -0
  41. justext/stoplists/Hindi.txt +373 -0
  42. justext/stoplists/Hungarian.txt +3446 -0
  43. justext/stoplists/Icelandic.txt +721 -0
  44. justext/stoplists/Ido.txt +46 -0
  45. justext/stoplists/Igbo.txt +149 -0
  46. justext/stoplists/Indonesian.txt +919 -0
  47. justext/stoplists/Irish.txt +216 -0
  48. justext/stoplists/Italian.txt +569 -0
  49. justext/stoplists/Javanese.txt +610 -0
  50. justext/stoplists/Kannada.txt +7060 -0
  51. justext/stoplists/Kazakh.txt +3671 -0
  52. justext/stoplists/Korean.txt +13061 -0
  53. justext/stoplists/Kurdish.txt +576 -0
  54. justext/stoplists/Kyrgyz.txt +3872 -0
  55. justext/stoplists/Latin.txt +1904 -0
  56. justext/stoplists/Latvian.txt +3611 -0
  57. justext/stoplists/Lithuanian.txt +4964 -0
  58. justext/stoplists/Lombard.txt +127 -0
  59. justext/stoplists/Low_Saxon.txt +172 -0
  60. justext/stoplists/Luxembourgish.txt +387 -0
  61. justext/stoplists/Macedonian.txt +928 -0
  62. justext/stoplists/Malay.txt +877 -0
  63. justext/stoplists/Malayalam.txt +11782 -0
  64. justext/stoplists/Maltese.txt +1388 -0
  65. justext/stoplists/Marathi.txt +2151 -0
  66. justext/stoplists/Neapolitan.txt +300 -0
  67. justext/stoplists/Nepali.txt +1540 -0
  68. justext/stoplists/Newar.txt +88 -0
  69. justext/stoplists/Norwegian_Bokmal.txt +474 -0
  70. justext/stoplists/Norwegian_Nynorsk.txt +350 -0
  71. justext/stoplists/Occitan.txt +499 -0
  72. justext/stoplists/Persian.txt +485 -0
  73. justext/stoplists/Piedmontese.txt +71 -0
  74. justext/stoplists/Polish.txt +3570 -0
  75. justext/stoplists/Portuguese.txt +490 -0
  76. justext/stoplists/Quechua.txt +266 -0
  77. justext/stoplists/Romanian.txt +993 -0
  78. justext/stoplists/Russian.txt +5088 -0
  79. justext/stoplists/Samogitian.txt +1759 -0
  80. justext/stoplists/Serbian.txt +1700 -0
  81. justext/stoplists/Serbo_Croatian.txt +2418 -0
  82. justext/stoplists/Sicilian.txt +514 -0
  83. justext/stoplists/Simple_English.txt +280 -0
  84. justext/stoplists/Slovak.txt +2417 -0
  85. justext/stoplists/Slovenian.txt +2343 -0
  86. justext/stoplists/Spanish.txt +304 -0
  87. justext/stoplists/Sundanese.txt +868 -0
  88. justext/stoplists/Swahili.txt +385 -0
  89. justext/stoplists/Swedish.txt +737 -0
  90. justext/stoplists/Tagalog.txt +148 -0
  91. justext/stoplists/Tamil.txt +6281 -0
  92. justext/stoplists/Telugu.txt +4566 -0
  93. justext/stoplists/Turkish.txt +3082 -0
  94. justext/stoplists/Turkmen.txt +3204 -0
  95. justext/stoplists/Ukrainian.txt +5025 -0
  96. justext/stoplists/Urdu.txt +233 -0
  97. justext/stoplists/Uzbek.txt +5927 -0
  98. justext/stoplists/Vietnamese.txt +292 -0
  99. justext/stoplists/Volapuk.txt +75 -0
  100. justext/stoplists/Walloon.txt +178 -0
  101. justext/stoplists/Waray_Waray.txt +11 -0
  102. justext/stoplists/Welsh.txt +550 -0
  103. justext/stoplists/West_Frisian.txt +251 -0
  104. justext/stoplists/Western_Panjabi.txt +260 -0
  105. justext/stoplists/Yoruba.txt +307 -0
  106. justext/utils.py +66 -0
  107. justext-4.0.0.dist-info/METADATA +126 -0
  108. justext-4.0.0.dist-info/RECORD +110 -0
  109. justext-4.0.0.dist-info/WHEEL +4 -0
  110. justext-4.0.0.dist-info/licenses/LICENSE.rst +24 -0
justext/core.py ADDED
@@ -0,0 +1,462 @@
1
+ # -*- coding: utf-8 -*-
2
+
3
+ """
4
+ Copyright (c) 2011 Jan Pomikalek
5
+
6
+ This software is licensed as described in the file LICENSE.rst.
7
+ """
8
+
9
+ from __future__ import absolute_import
10
+ from __future__ import division, print_function, unicode_literals
11
+
12
+ import codecs
13
+ import re
14
+ import lxml.html
15
+ import lxml.sax
16
+
17
+ try:
18
+ from functools import lru_cache
19
+ except ImportError:
20
+ from backports.functools_lru_cache import lru_cache
21
+
22
+ from lxml.html.clean import Cleaner
23
+ from xml.sax.handler import ContentHandler
24
+ from .paragraph import Paragraph
25
+ from ._compat import unicode, ignored, zip
26
+ from .utils import is_blank
27
+
28
+
29
+ MAX_LINK_DENSITY_DEFAULT = 0.2
30
+ LENGTH_LOW_DEFAULT = 70
31
+ LENGTH_HIGH_DEFAULT = 200
32
+ STOPWORDS_LOW_DEFAULT = 0.30
33
+ STOPWORDS_HIGH_DEFAULT = 0.32
34
+ NO_HEADINGS_DEFAULT = False
35
+ # Short and near-good headings within MAX_HEADING_DISTANCE characters before
36
+ # a good paragraph are classified as good unless --no-headings is specified.
37
+ MAX_HEADING_DISTANCE_DEFAULT = 200
38
+ # Maximum distance (in paragraphs) of a short/near-good paragraph from a good
39
+ # paragraph for the good one to be taken into account as its neighbour.
40
+ MAX_GOOD_DISTANCE_DEFAULT = None
41
+ PARAGRAPH_TAGS = frozenset({
42
+ 'body', 'blockquote', 'caption', 'center', 'col', 'colgroup', 'dd',
43
+ 'div', 'dl', 'dt', 'fieldset', 'figcaption', 'form', 'legend', 'optgroup',
44
+ 'option', 'p', 'pre', 'table', 'td', 'textarea', 'tfoot', 'th', 'thead', 'tr',
45
+ 'ul', 'li', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
46
+ })
47
+ DEFAULT_ENCODING = 'utf8'
48
+ DEFAULT_ENC_ERRORS = 'replace'
49
+ CHARSET_META_TAG_PATTERN = re.compile(br"""<meta[^>]+charset=["']?([^'"/>\s]+)""", re.IGNORECASE)
50
+ XML_DECLARATION_ENCODING_PATTERN = re.compile(br"""\s*<\?xml[^>]+encoding=["']([^'"]+)""")
51
+ # <meta charset> labels that browsers decode with another codec than Python does
52
+ # https://encoding.spec.whatwg.org/#names-and-labels
53
+ _BROWSER_CODEC_LABELS = {
54
+ "cp1252": ["ansi_x3.4-1968", "ascii", "cp819", "csisolatin1", "ibm819", "iso-8859-1", "iso-ir-100",
55
+ "iso8859-1", "iso88591", "iso_8859-1", "iso_8859-1:1987", "l1", "latin1", "us-ascii", "x-cp1252"],
56
+ "gb18030": ["chinese", "csgb2312", "csiso58gb231280", "gb2312", "gb_2312", "gb_2312-80", "gbk", "iso-ir-58",
57
+ "x-gbk"],
58
+ # close to browsers, not identical: a few code points differ (0x8160 is U+FF5E, not U+301C)
59
+ "cp932": ["csshiftjis", "ms932", "ms_kanji", "shift-jis", "shift_jis", "sjis", "windows-31j", "x-sjis"],
60
+ "cp949": ["cseuckr", "csksc56011987", "euc-kr", "iso-ir-149", "korean", "ks_c_5601-1987", "ks_c_5601-1989",
61
+ "ksc5601", "ksc_5601", "windows-949"],
62
+ # an ASCII-compatible <meta> can't be in UTF-16, browsers use UTF-8 then
63
+ "utf-8": ["utf-16", "utf-16le", "utf-16be"],
64
+ "cp874": ["dos-874", "iso-8859-11", "iso8859-11", "iso885911", "tis-620", "windows-874"],
65
+ "iso8859-8": ["csiso88598i", "iso-8859-8-i", "logical"],
66
+ "cp1254": ["csisolatin5", "iso-8859-9", "iso-ir-148", "iso8859-9", "iso88599", "iso_8859-9",
67
+ "iso_8859-9:1989", "l5", "latin5"],
68
+ }
69
+ _CODEC_BY_LABEL = {label: codec for codec, labels in _BROWSER_CODEC_LABELS.items() for label in labels}
70
+ # windows codecs whose undefined bytes are all in 0x80-0x9F, browsers decode them to C1 controls
71
+ _C1_CONTROL_CODECS = frozenset({"cp1250", "cp1251", "cp1252", "cp1254", "cp1258"})
72
+ GOOD_OR_BAD = {'good', 'bad'}
73
+ GOOD_BAD_OR_NEARGOOD = GOOD_OR_BAD | {'neargood'}
74
+
75
+
76
+ class JustextError(Exception):
77
+ "Base class for jusText exceptions."
78
+
79
+
80
+ class JustextInvalidOptions(JustextError):
81
+ pass
82
+
83
+
84
+ class JustextDecodeError(JustextError, UnicodeDecodeError):
85
+ "Raised when the HTML can't be decoded to Unicode with `errors='strict'`."
86
+
87
+
88
+ def html_to_dom(html, default_encoding=DEFAULT_ENCODING, encoding=None, errors=DEFAULT_ENC_ERRORS):
89
+ """Converts HTML to DOM."""
90
+ if isinstance(html, unicode):
91
+ decoded_html = html
92
+ # encode HTML for case it's XML with encoding declaration
93
+ forced_encoding = encoding if encoding else default_encoding
94
+ html = html.encode(forced_encoding, errors)
95
+ else:
96
+ decoded_html = decode_html(html, default_encoding, encoding, errors)
97
+
98
+ try:
99
+ dom = lxml.html.fromstring(decoded_html, parser=lxml.html.HTMLParser())
100
+ except ValueError:
101
+ # Unicode strings with encoding declaration are not supported.
102
+ # for XHTML files with encoding declaration, use the declared encoding
103
+ # the HTML parser ignores the XML declaration, so pass the already decoded text in a known encoding
104
+ dom = lxml.html.fromstring(decoded_html.encode("utf-8"), parser=lxml.html.HTMLParser(encoding="utf-8"))
105
+
106
+ return dom
107
+
108
+
109
+ def _decode(data, encoding, errors):
110
+ try:
111
+ return data.decode(encoding, errors)
112
+ except UnicodeDecodeError as e:
113
+ raise JustextDecodeError(*e.args)
114
+
115
+
116
+ def _decode_as_c1_controls(error):
117
+ "Decodes undefined bytes to the C1 control characters of the same value."
118
+ return error.object[error.start:error.end].decode("latin-1"), error.end
119
+
120
+
121
+ codecs.register_error("justext.c1_controls", _decode_as_c1_controls)
122
+
123
+
124
+ def decode_html(html, default_encoding=DEFAULT_ENCODING, encoding=None, errors=DEFAULT_ENC_ERRORS):
125
+ """
126
+ Converts a `html` containing an HTML page into Unicode.
127
+ Tries to guess character encoding from byte order mark or meta tag.
128
+ """
129
+ if isinstance(html, unicode):
130
+ return html
131
+
132
+ if encoding:
133
+ return _decode(html, encoding, errors)
134
+
135
+ # byte order mark wins over the declared encoding
136
+ # https://encoding.spec.whatwg.org/#bom-sniff
137
+ if html.startswith(codecs.BOM_UTF8):
138
+ return _decode(html, "utf-8-sig", errors)
139
+ # WHATWG leaves UTF-32 out, but its BOMs are checked here too. The LE
140
+ # one starts with the UTF-16 LE BOM, so it has to come first.
141
+ if html.startswith((codecs.BOM_UTF32_LE, codecs.BOM_UTF32_BE)):
142
+ return _decode(html, "utf-32", errors)
143
+ if html.startswith((codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE)):
144
+ return _decode(html, "utf-16", errors)
145
+
146
+ match = CHARSET_META_TAG_PATTERN.search(html) or XML_DECLARATION_ENCODING_PATTERN.match(html)
147
+ if match:
148
+ declared_encoding = match.group(1).decode("ASCII")
149
+ declared_encoding = _CODEC_BY_LABEL.get(declared_encoding.lower(), declared_encoding)
150
+ # proceed unknown encoding as if it wasn't found at all
151
+ with ignored(LookupError):
152
+ codec = codecs.lookup(declared_encoding).name
153
+ return _decode(html, codec, "justext.c1_controls" if codec in _C1_CONTROL_CODECS else errors)
154
+
155
+ # unknown encoding
156
+ try:
157
+ # try UTF-8 first
158
+ return html.decode("utf8")
159
+ except UnicodeDecodeError:
160
+ # try lucky with default encoding
161
+ return _decode(html, default_encoding, errors)
162
+
163
+
164
+ def preprocessor(dom):
165
+ "Removes unwanted parts of DOM."
166
+ options = {
167
+ "processing_instructions": False,
168
+ "remove_unknown_tags": False,
169
+ "safe_attrs_only": False,
170
+ "page_structure": False,
171
+ "annoying_tags": False,
172
+ "frames": False,
173
+ "meta": False,
174
+ "links": False,
175
+ "javascript": False,
176
+ "scripts": True,
177
+ "comments": True,
178
+ "style": True,
179
+ "embedded": True,
180
+ "forms": True,
181
+ "kill_tags": ("head", "nav"),
182
+ }
183
+ cleaner = Cleaner(**options)
184
+ dom = cleaner.clean_html(dom)
185
+
186
+ # <footer> inside <blockquote> holds the attribution of the quote
187
+ for footer in dom.xpath("//footer[not(ancestor::blockquote)]"):
188
+ footer.drop_tree()
189
+
190
+ return dom
191
+
192
+
193
+ # super(...).__init__() breaks Python 2.7 - TypeError: super() argument 1 must be type, not classobj
194
+ # noinspection PyMissingConstructor
195
+ class ParagraphMaker(ContentHandler):
196
+ """
197
+ A class for converting a HTML page represented as a DOM object into a list
198
+ of paragraphs.
199
+ """
200
+
201
+ @classmethod
202
+ def make_paragraphs(cls, root):
203
+ """Converts DOM into paragraphs."""
204
+ handler = cls()
205
+ lxml.sax.saxify(root, handler)
206
+ return handler.paragraphs
207
+
208
+ def __init__(self):
209
+ self.path = PathInfo()
210
+ self.paragraphs = []
211
+ self.paragraph = None
212
+ self.link = False
213
+ self.br = False
214
+ self._start_new_pragraph()
215
+
216
+ def _start_new_pragraph(self):
217
+ if self.paragraph and self.paragraph.contains_text():
218
+ self.paragraphs.append(self.paragraph)
219
+
220
+ self.paragraph = Paragraph(self.path)
221
+
222
+ def startElementNS(self, name, qname, attrs):
223
+ name = name[1]
224
+ self.path.append(name)
225
+
226
+ if name in PARAGRAPH_TAGS or (name == "br" and self.br):
227
+ if name == "br":
228
+ # the <br><br> is a paragraph separator and should
229
+ # not be included in the number of tags within the
230
+ # paragraph
231
+ self.paragraph.tags_count -= 1
232
+ self._start_new_pragraph()
233
+ else:
234
+ self.br = bool(name == "br")
235
+ if self.br:
236
+ self.paragraph.append_text(' ')
237
+ elif name == 'a':
238
+ self.link = True
239
+ self.paragraph.tags_count += 1
240
+
241
+ def endElementNS(self, name, qname):
242
+ name = name[1]
243
+ self.path.pop()
244
+
245
+ if name in PARAGRAPH_TAGS:
246
+ self._start_new_pragraph()
247
+ if name == 'a':
248
+ self.link = False
249
+
250
+ def endDocument(self):
251
+ self._start_new_pragraph()
252
+
253
+ def characters(self, content):
254
+ if is_blank(content):
255
+ return
256
+
257
+ text = self.paragraph.append_text(content)
258
+
259
+ if self.link:
260
+ self.paragraph.chars_count_in_links += len(text)
261
+ self.br = False
262
+
263
+
264
+ class PathInfo(object):
265
+ def __init__(self):
266
+ # list of triples (tag name, order, children)
267
+ self._elements = []
268
+
269
+ @property
270
+ def dom(self):
271
+ return ".".join(e[0] for e in self._elements)
272
+
273
+ @property
274
+ def xpath(self):
275
+ return "/" + "/".join("%s[%d]" % e[:2] for e in self._elements)
276
+
277
+ def append(self, tag_name):
278
+ children = self._get_children()
279
+ order = children.get(tag_name, 0) + 1
280
+ children[tag_name] = order
281
+
282
+ xpath_part = (tag_name, order, {})
283
+ self._elements.append(xpath_part)
284
+
285
+ return self
286
+
287
+ def _get_children(self):
288
+ if not self._elements:
289
+ return {}
290
+
291
+ return self._elements[-1][2]
292
+
293
+ def pop(self):
294
+ self._elements.pop()
295
+ return self
296
+
297
+
298
+ @lru_cache(maxsize=128) # 100 stoplists
299
+ def define_stoplist(stoplist):
300
+ "Lower-case all words in stoplist and create frozen set."
301
+ stoplist = frozenset(w.lower() for w in stoplist)
302
+ return stoplist
303
+
304
+
305
+ def classify_paragraphs(paragraphs, stoplist, length_low=LENGTH_LOW_DEFAULT,
306
+ length_high=LENGTH_HIGH_DEFAULT, stopwords_low=STOPWORDS_LOW_DEFAULT,
307
+ stopwords_high=STOPWORDS_HIGH_DEFAULT, max_link_density=MAX_LINK_DENSITY_DEFAULT,
308
+ no_headings=NO_HEADINGS_DEFAULT):
309
+ "Context-free paragraph classification."
310
+
311
+ stoplist = define_stoplist(stoplist)
312
+ for paragraph in paragraphs:
313
+ length = len(paragraph)
314
+ stopword_density = paragraph.stopwords_density(stoplist)
315
+ link_density = paragraph.links_density()
316
+ paragraph.heading = bool(not no_headings and paragraph.is_heading)
317
+
318
+ if link_density > max_link_density:
319
+ paragraph.cf_class = 'bad'
320
+ elif 'select' in paragraph.dom_path:
321
+ paragraph.cf_class = 'bad'
322
+ elif length < length_low:
323
+ if paragraph.chars_count_in_links > 0:
324
+ paragraph.cf_class = 'bad'
325
+ else:
326
+ paragraph.cf_class = 'short'
327
+ elif stopword_density >= stopwords_high:
328
+ if length > length_high:
329
+ paragraph.cf_class = 'good'
330
+ else:
331
+ paragraph.cf_class = 'neargood'
332
+ elif stopword_density >= stopwords_low:
333
+ paragraph.cf_class = 'neargood'
334
+ else:
335
+ paragraph.cf_class = 'bad'
336
+
337
+ if ('\xa9' in paragraph.text) or ('&copy' in paragraph.text):
338
+ # The copyright symbol hints at boilerplate but it also appears
339
+ # inside good paragraphs, so only lower the class by one step
340
+ # instead of rejecting the paragraph outright.
341
+ if paragraph.cf_class == 'good':
342
+ paragraph.cf_class = 'neargood'
343
+ elif paragraph.cf_class == 'short':
344
+ paragraph.cf_class = 'bad'
345
+
346
+
347
+ def _prev_neighbours(paragraphs, classes, max_good_distance):
348
+ """
349
+ Yield, for each paragraph, the class of the closest previous paragraph
350
+ with a class from classes, up to max_good_distance paragraphs far
351
+ (None for no limit), otherwise 'bad'. It is lazy, so a class changed by
352
+ the consumer is seen by the following paragraphs.
353
+ """
354
+ if max_good_distance is None:
355
+ max_good_distance = float('inf')
356
+ neighbour, neighbour_index = 'bad', float('-inf')
357
+ for i, paragraph in enumerate(paragraphs):
358
+ yield neighbour if i - neighbour_index <= max_good_distance else 'bad'
359
+ if paragraph.class_type in classes:
360
+ neighbour, neighbour_index = paragraph.class_type, i
361
+
362
+
363
+ def _next_neighbours(paragraphs, classes, max_good_distance):
364
+ """The same as _prev_neighbours, looking at the following paragraphs."""
365
+ return reversed(list(_prev_neighbours(paragraphs[::-1], classes, max_good_distance)))
366
+
367
+
368
+ def revise_paragraph_classification(paragraphs, max_heading_distance=MAX_HEADING_DISTANCE_DEFAULT,
369
+ max_good_distance=MAX_GOOD_DISTANCE_DEFAULT):
370
+ """
371
+ Context-sensitive paragraph classification. Assumes that classify_pragraphs
372
+ has already been called.
373
+ """
374
+
375
+ # copy classes before the heading pass, it looks at the following paragraphs
376
+ for paragraph in paragraphs:
377
+ paragraph.class_type = paragraph.cf_class
378
+
379
+ # good headings
380
+ for i, paragraph in enumerate(paragraphs):
381
+ if not (paragraph.heading and paragraph.class_type == 'short'):
382
+ continue
383
+ j = i + 1
384
+ distance = 0
385
+ while j < len(paragraphs) and distance <= max_heading_distance:
386
+ if paragraphs[j].class_type == 'good':
387
+ paragraph.class_type = 'neargood'
388
+ break
389
+ distance += len(paragraphs[j].text)
390
+ j += 1
391
+
392
+ # classify short
393
+ prev_neighbours = list(_prev_neighbours(paragraphs, GOOD_OR_BAD, max_good_distance))
394
+ next_neighbours = list(_next_neighbours(paragraphs, GOOD_OR_BAD, max_good_distance))
395
+ prev_or_neargood = list(_prev_neighbours(paragraphs, GOOD_BAD_OR_NEARGOOD, max_good_distance))
396
+ next_or_neargood = list(_next_neighbours(paragraphs, GOOD_BAD_OR_NEARGOOD, max_good_distance))
397
+ new_classes = {}
398
+ for i, paragraph in enumerate(paragraphs):
399
+ if paragraph.class_type != 'short':
400
+ continue
401
+ prev_neighbour = prev_neighbours[i]
402
+ next_neighbour = next_neighbours[i]
403
+ if prev_neighbour == 'good' and next_neighbour == 'good':
404
+ new_classes[i] = 'good'
405
+ elif prev_neighbour == 'bad' and next_neighbour == 'bad':
406
+ new_classes[i] = 'bad'
407
+ # it must be set(['good', 'bad'])
408
+ elif (prev_neighbour == 'bad' and prev_or_neargood[i] == 'neargood') or \
409
+ (next_neighbour == 'bad' and next_or_neargood[i] == 'neargood'):
410
+ new_classes[i] = 'good'
411
+ else:
412
+ new_classes[i] = 'bad'
413
+
414
+ for i, c in new_classes.items():
415
+ paragraphs[i].class_type = c
416
+
417
+ # revise neargood, a revised neargood is the previous neighbour of the next one
418
+ next_neighbours = _next_neighbours(paragraphs, GOOD_OR_BAD, max_good_distance)
419
+ prev_neighbours = _prev_neighbours(paragraphs, GOOD_OR_BAD, max_good_distance)
420
+ for paragraph, prev_neighbour, next_neighbour in zip(paragraphs, prev_neighbours, next_neighbours):
421
+ if paragraph.class_type != 'neargood':
422
+ continue
423
+ if (prev_neighbour, next_neighbour) == ('bad', 'bad'):
424
+ paragraph.class_type = 'bad'
425
+ else:
426
+ paragraph.class_type = 'good'
427
+
428
+ # more good headings
429
+ for i, paragraph in enumerate(paragraphs):
430
+ if not (paragraph.heading and paragraph.class_type == 'bad' and paragraph.cf_class != 'bad'):
431
+ continue
432
+ j = i + 1
433
+ distance = 0
434
+ while j < len(paragraphs) and distance <= max_heading_distance:
435
+ if paragraphs[j].class_type == 'good':
436
+ paragraph.class_type = 'good'
437
+ break
438
+ distance += len(paragraphs[j].text)
439
+ j += 1
440
+
441
+
442
+ def justext(html_text, stoplist, length_low=LENGTH_LOW_DEFAULT,
443
+ length_high=LENGTH_HIGH_DEFAULT, stopwords_low=STOPWORDS_LOW_DEFAULT,
444
+ stopwords_high=STOPWORDS_HIGH_DEFAULT, max_link_density=MAX_LINK_DENSITY_DEFAULT,
445
+ max_heading_distance=MAX_HEADING_DISTANCE_DEFAULT, no_headings=NO_HEADINGS_DEFAULT,
446
+ encoding=None, default_encoding=DEFAULT_ENCODING,
447
+ enc_errors=DEFAULT_ENC_ERRORS, preprocessor=preprocessor,
448
+ max_good_distance=MAX_GOOD_DISTANCE_DEFAULT):
449
+ """
450
+ Converts an HTML page into a list of classified paragraphs. Each paragraph
451
+ is represented as instance of class ˙˙justext.paragraph.Paragraph˙˙.
452
+ """
453
+ dom = html_to_dom(html_text, default_encoding, encoding, enc_errors)
454
+ dom = preprocessor(dom)
455
+
456
+ paragraphs = ParagraphMaker.make_paragraphs(dom)
457
+
458
+ classify_paragraphs(paragraphs, stoplist, length_low, length_high,
459
+ stopwords_low, stopwords_high, max_link_density, no_headings)
460
+ revise_paragraph_classification(paragraphs, max_heading_distance, max_good_distance)
461
+
462
+ return paragraphs
justext/paragraph.py ADDED
@@ -0,0 +1,66 @@
1
+ # -*- coding: utf-8 -*-
2
+
3
+ from __future__ import absolute_import
4
+ from __future__ import division, print_function, unicode_literals
5
+
6
+ import re
7
+
8
+ from .utils import normalize_whitespace
9
+
10
+
11
+ HEADINGS_PATTERN = re.compile(r"\bh\d\b")
12
+
13
+
14
+ class Paragraph(object):
15
+ """Object representing one block of text in HTML."""
16
+ def __init__(self, path):
17
+ self.dom_path = path.dom
18
+ self.xpath = path.xpath
19
+ self.text_nodes = []
20
+ self.chars_count_in_links = 0
21
+ self.tags_count = 0
22
+ self.class_type = "" # short | neargood | good | bad
23
+
24
+ @property
25
+ def is_heading(self):
26
+ return bool(HEADINGS_PATTERN.search(self.dom_path))
27
+
28
+ @property
29
+ def is_boilerplate(self):
30
+ return self.class_type != "good"
31
+
32
+ @property
33
+ def text(self):
34
+ text = "".join(self.text_nodes)
35
+ return normalize_whitespace(text.strip())
36
+
37
+ def __len__(self):
38
+ return len(self.text)
39
+
40
+ @property
41
+ def words_count(self):
42
+ return len(self.text.split())
43
+
44
+ def contains_text(self):
45
+ return bool(self.text_nodes)
46
+
47
+ def append_text(self, text):
48
+ text = normalize_whitespace(text)
49
+ self.text_nodes.append(text)
50
+ return text
51
+
52
+ def stopwords_count(self, stopwords):
53
+ return sum(word.lower() in stopwords for word in self.text.split())
54
+
55
+ def stopwords_density(self, stopwords):
56
+ if self.words_count == 0:
57
+ return 0
58
+
59
+ return self.stopwords_count(stopwords) / self.words_count
60
+
61
+ def links_density(self):
62
+ text_length = len(self.text)
63
+ if text_length == 0:
64
+ return 0
65
+
66
+ return self.chars_count_in_links / text_length