tiendung's picture
update
e7b86d8
Raw
History Blame Contribute Delete
2.12 kB
import requests, os, sys, json, lzma
from bs4 import BeautifulSoup # pip install beautifulsoup4
import trafilatura # pip install trafilatura
from multiprocessing import Process
from multiprocessing.pool import Pool
stories = []
with lzma.open("3-stories.jsonl.xz", "rt") as fin:
for idx, line in enumerate(fin):
data = json.loads(line)
print(data["title"])
data["_id"] = idx
stories.append(data)
print(len(stories))
#sys.exit()
def combine(story):
_id = story["_id"]
urls_contents = {}
chapters_file = f"stories/{_id}_chapters.jsonl"
if not os.path.exists(chapters_file): return _id
story_file = f"stories/{_id}.jsonl"
if os.path.exists(story_file):
x = os.path.getsize(story_file) / os.path.getsize(chapters_file)
if x > 0.8:
try:
with open(story_file, "rt") as fin:
for line in fin:
json.loads(line)
return _id
except:
False
with open(chapters_file, "rt") as f:
for l in f:
d = json.loads(l)
urls_contents[d["url"]] = d["content"]
title = story["title"]; cat = story["cat"]
text = f"Truyện: {title}\nThể loại: {cat}"
count = 0
chapter_urls = set()
for chapter in story["chapters"]:
t = chapter["title"]
u = chapter["url"]
if u not in chapter_urls:
chapter_urls.add(u)
if u in urls_contents:
count += 1
c = urls_contents[u]
text += f"""
{t}
{c}
"""
if count > (2*len(chapter_urls)) // 3:
with open(story_file, "wt") as fout:
fout.write(json.dumps({
"text": text,
"url": story["url"]
}, ensure_ascii=False) + "\n")
return _id
with Pool() as pool:
count = 0
for story_id in pool.imap_unordered(combine, stories):
count += 1
print(count, story_id, "DONE!")