#!/usr/bin/env python3 # http://inamidst.com/saxo/ # Created by Sean B. Palmer import json import re import saxo upper = tuple("ABCDEFGHIJKLMNOPQRSTUVWXYZ") lower = tuple("abcdefghijklmnopqrstuvwxyz") abbreviations = upper + lower + ("etc", "ca", "cf", "Co", "Ltd", "Inc", "Mt", "Mr", "Mrs", "Dr", "Ms", "Rev", "Fr", "St", "Sgt", "pron", "approx", "lit", "syn", "transl", "sess", "fl", "Op", "Dec", "Brig", "Gen", "Bros") abbreviations_pattern = r"(?]*>.*?
|") and block.endswith("
"): return True for text in skip: if text in block: return True return False def skip_text_block(block): if len(block) < 32: return True if not block: return True return False def scrape(block): block = block.replace("", "|") block = block.replace("", "|") block = block.replace("\n", " / ") block = regex_style.sub("", block) block = regex_tag.sub("", block) return regex_footnote.sub("", block) for attempt in range(2): # See if the article actually exists first, with following on page = saxo.request("https://%s.wikipedia.org/wiki/%s" % (language, underscored(term)), follow=True) # @@ it's an int here? huh if page["status"] != 200: debug.append("%s gave %s" % (page["url"], page["status"])) term = search(term) if not term: return "Google had no results" continue # Don't think they have those old 200 Redirects now text = regex_tr.sub("", page["text"]) blocks = regex_block.findall(text) if not blocks: debug.append("%s had no blocks" % page["url"]) term = search(term) continue # Filter out stuff we don't want blocks = (block for block in blocks if not skip_html_block(block)) blocks = (scrape(block) for block in blocks) blocks = (block for block in blocks if not skip_text_block(block)) block = next(blocks) try: block += " " + next(blocks) + " " + next(blocks) except StopIteration: ... sentence_match = regex_sentence.match(block) if not sentence_match: debug.append("%s had no sentences" % page["url"]) term = search(term) continue sentence = sentence_match.group(1) if 'href="/wiki/Category:Disambiguation_pages"' in page["text"]: sentence = "[Disambiguation] " + sentence if len(sentence) < 128: block = block[len(sentence):].lstrip() sentence_match2 = regex_sentence.match(block) if sentence_match2: sentence += " " + sentence_match2.group(1) maxlength = 275 ellipsis = False while len(utf8(sentence)) > maxlength: sentence = " ".join(sentence.split(" ")[:-1]) ellipsis = True if ellipsis is True: sentence += " [...]" sentence = sentence.replace('"', "'") if sentence.endswith(":"): sentence = sentence[:-1] + "..." # url = page["url"] # term = spaced(term) sentence = sentence.replace("\r", "") sentence = sentence.replace("\n", "") return '"' + sentence + '" - ' + page["url"] return "Article not found: " + " | ".join(debug)