5 Written by BroytMann. Copyright (C) 1997-2007 PhiloSoft Design
10 from m_lib.defenc import default_encoding
11 current_charset = default_encoding.replace("windows-", "cp")
12 DEFAULT_CHARSET = "cp1251" # Stupid default for Russian Cyrillic
15 from parse_html_beautifulsoup import parse_html as _parse_html
17 from parse_html_htmlparser import parse_html as _parse_html
21 entity_re = re.compile("(&#[0-9]+;)")
23 def recode_entities(title, charset):
25 for part in entity_re.split(title):
26 if entity_re.match(part):
27 part = unichr(int(part[2:-1])).encode(charset, "replace")
30 return ''.join(output)
33 def parse_html(filename, charset=None, log=None):
36 codecs.lookup(charset) # In case of unknown charset...
37 except (ValueError, LookupError):
38 charset = None # ...try charset from HTML
40 parser = _parse_html(filename, charset)
43 if not parser.charset:
45 unicode(title, "ascii")
46 except UnicodeDecodeError:
47 parser.charset = DEFAULT_CHARSET
50 parser.charset = parser.charset.replace("windows-", "cp").lower()
52 if parser.charset and (parser.charset <> current_charset):
54 if parser.meta_charset:
55 if log: log(" META charset : %s" % parser.charset)
57 if log: log(" charset : %s" % parser.charset)
58 if log: log(" title : %s" % title)
59 title = unicode(title, parser.charset, "replace").encode(current_charset, "replace")
60 if log: log(" current charset: %s" % current_charset)
61 if log: log(" converted title: %s" % title)
63 if log: log(" unknown charset: `%s' or `%s'" % (parser.charset, current_charset))
65 parser.title = recode_entities(title, current_charset)
69 if __name__ == '__main__':
71 parser = parse_html(sys.argv[1], current_charset)