Skip to content

Instantly share code, notes, and snippets.

@meseta
Last active June 16, 2021 21:53
Show Gist options
  • Save meseta/028c390355d2cb0764311eb79cb3f751 to your computer and use it in GitHub Desktop.
Save meseta/028c390355d2cb0764311eb79cb3f751 to your computer and use it in GitHub Desktop.
Converts quora dumps that you can request Quora to send you (multiple zip files) into parsed json and markdown
""" Converts quora dumps that you can request Quora to send you (multiple zip files) into parsed json and markdown
To use:
1. install dateparser, beautifulsoup4, markdownify
2. copy the zips you've received to ./data, make sure to keep only the ones containing answers (some will
contain comments, blog posts, and other metadata)
3. run this script
4. see ./output folder
License (MIT):
Copyright 2021 Yuan Gao
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
import glob
import re
import json
import dateparser
import os
from zipfile import ZipFile
from bs4 import BeautifulSoup
from urllib.parse import unquote
# regex for removing the quora redirect from links
link_redirect = re.compile("https://www\.quora\.com/_/redirect\?sig=[a-f0-9]+&url=")
def handle_html(html_text):
""" Handles an HTML document, returning each Q/A entry as a dict, and list of images used """
soup = BeautifulSoup(html_text, "html.parser")
entries = soup.find("div").find_all("p", recursive=False)
output = []
images = []
for idx, entry in enumerate(entries):
s_question, s_answer, s_created, _ = entry.find_all("div", recursive=False)
question_text = s_question.find("span", {"class": "rendered_qtext"}).text
created = dateparser.parse(s_created.find("span").text)
answer = s_answer.find("span", {"class": "rendered_qtext"})
# convert image links
for img in answer.find_all("img"):
images.append(img["src"])
linebreak = soup.new_tag("br") # image tag needs a linebreak after
img.insert_after(linebreak)
# convert links
for span in answer.find_all("span", {"class": "qlink_container"}):
link = span.find("a")
link["href"] = unquote(link_redirect.sub("", (link["href"])))
span.replace_with(link)
# convert latex
for span in answer.find_all("span", {"class": "render_latex"}):
latex = span.text.removeprefix("[math]").removesuffix("[/math]")
new_span = soup.new_tag("span")
new_span.string = f"${latex}$"
span.replace_with(new_span)
output.append({
"question": str(question_text),
"answer": md(str(answer)),
"created": created.isoformat()
})
return output, images
# "business end" of the script
all_outputs = []
os.makedirs("output", exist_ok=True)
for zip_file in glob.glob("./data/*.zip"):
with ZipFile(zip_file) as zf:
# parse the index.html
with zf.open("index.html") as fp:
html_text = fp.read()
outputs, images = handle_html(html_text)
all_outputs.extend(outputs)
# copy images from zip file to output folder
for image in images:
zf.extract(image, "output")
os.rename(f"output/{image}", f"output/{image}")
# output json
with open(f"output/data.json", "w") as fp:
json.dump(all_outputs, fp)
# optional giant markdown file with everything in it
with open(f"output/preview_all.md", "w") as fp:
for output in all_outputs:
fp.write(f"""# {output["question"]}\n\n{output["answer"]}\n\n(created: {output["created"]})\n___\n""")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment