| 1 |
|
| 2 |
"""补充 8105 中汉字的拼音数据""" |
| 3 |
from collections import namedtuple |
| 4 |
import re |
| 5 |
import sys |
| 6 |
|
| 7 |
from pyquery import PyQuery |
| 8 |
import requests |
| 9 |
|
| 10 |
re_pinyin = re.compile(r'拼音:(?P<pinyin>\S+) ') |
| 11 |
re_code = re.compile(r'统一码\w?:(?P<code>\S+) ') |
| 12 |
re_alternate = re.compile(r'异体字:\s+?(?P<alternate>\S+)') |
| 13 |
HanziInfo = namedtuple('HanziInfo', 'pinyin code alternate') |
| 14 |
|
| 15 |
|
| 16 |
def fetch_html(url, params): |
| 17 |
response = requests.get(url, params=params) |
| 18 |
return response.content |
| 19 |
|
| 20 |
|
| 21 |
def fetch_info(hanzi): |
| 22 |
url = 'http://www.guoxuedashi.com/zidian/so.php' |
| 23 |
params = { |
| 24 |
'sokeyzi': hanzi, |
| 25 |
'kz': 1, |
| 26 |
'submit': '', |
| 27 |
} |
| 28 |
html = fetch_html(url, params) |
| 29 |
pq = PyQuery(html) |
| 30 |
pq = PyQuery(pq('table.zui td')[1]) |
| 31 |
text = pq('tr').text() |
| 32 |
text_alternate = pq(html)('.info_txt2')('em').text() |
| 33 |
|
| 34 |
pinyin = '' |
| 35 |
pinyin_match = re_pinyin.search(text) |
| 36 |
if pinyin_match is not None: |
| 37 |
pinyin = pinyin_match.group('pinyin') |
| 38 |
code = re_code.search(text).group('code') |
| 39 |
alternate = '' |
| 40 |
alternate_match = re_alternate.search(text_alternate) |
| 41 |
if alternate_match is not None: |
| 42 |
alternate = alternate_match.group('alternate') |
| 43 |
|
| 44 |
return HanziInfo(pinyin, code, alternate) |
| 45 |
|
| 46 |
|
| 47 |
def parse_hanzi(hanzi): |
| 48 |
info = fetch_info(hanzi) |
| 49 |
if (not info.pinyin) and info.alternate: |
| 50 |
alternate = fetch_info(info.alternate) |
| 51 |
else: |
| 52 |
alternate = '' |
| 53 |
return HanziInfo(info.pinyin, info.code, alternate) |
| 54 |
|
| 55 |
|
| 56 |
def main(lines): |
| 57 |
for line in lines: |
| 58 |
if line.startswith('# U+') and '<-' in line: |
| 59 |
|
| 60 |
code = line.split(':')[0].strip('# ') |
| 61 |
|
| 62 |
code = code[2:] |
| 63 |
info = parse_hanzi(code) |
| 64 |
pinyin = info.pinyin |
| 65 |
extra = '' |
| 66 |
if (not pinyin) and info.alternate: |
| 67 |
alternate = info.alternate |
| 68 |
pinyin = alternate.pinyin |
| 69 |
extra = ' => U+{0}'.format(alternate.code) |
| 70 |
if ',' in pinyin: |
| 71 |
first_pinyin, extra_pinyin = pinyin.split(',', 1) |
| 72 |
pinyin = first_pinyin |
| 73 |
extra += ' ?-> ' + extra_pinyin |
| 74 |
if pinyin: |
| 75 |
line = line.strip() |
| 76 |
|
| 77 |
line = line[2:] |
| 78 |
line = line.replace('<-', pinyin) |
| 79 |
if extra: |
| 80 |
line += extra |
| 81 |
yield line.strip() |
| 82 |
|
| 83 |
if __name__ == '__main__': |
| 84 |
args = sys.argv[1:] |
| 85 |
input_file = args[0] |
| 86 |
with open(input_file) as fp: |
| 87 |
for line in main(fp): |
| 88 |
print(line) |