Last active
April 26, 2020 12:52
-
-
Save kzinmr/c8e009ff5d155be5d5468c4b054a1c80 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from collections import OrderedDict | |
from html.parser import HTMLParser | |
import json | |
class MyHTMLParser(HTMLParser): | |
debug = False | |
def __init__(self): | |
HTMLParser.__init__(self) | |
self.recording = 0 | |
self.data = [] | |
def handle_data(self, data): | |
''' コンテンツ抽出を実装する処理 ''' | |
if self.debug: | |
print("Data :", data) | |
else: | |
self.data.append(data.replace(' ', '')) | |
with open('kou_h21.html', encoding='cp932') as fp: | |
lines = fp.read().splitlines() | |
lines_contents = lines[lines.index('<!-- コンテンツ -->'):lines.index('<div class="contentsMenu">')] | |
lines_contents = list(filter(None, lines_contents)) | |
parser = MyHTMLParser() | |
lines_contents_parsed = [parser.feed(line) for line in lines_contents] | |
dataiter = iter(parser.data) | |
data = OrderedDict() | |
l = '' | |
key = '' | |
subkey = '' | |
while l not in data: | |
if l not in data and l.startswith('大分類\u3000'): | |
data[l] = {} # len('大分類\u3000') | |
l = next(dataiter) | |
else: | |
key = l | |
while True: | |
if l in data: | |
key = l | |
elif l.startswith('中分類\u3000'): | |
subkey = l | |
data[key][subkey] = [] | |
elif l[:3].isnumeric(): | |
data[key][subkey].append(l) | |
try: | |
l = next(dataiter) | |
except StopIteration: | |
break | |
print(json.dumps(data, ensure_ascii=False, indent=4)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
OUTPUT