Package encutils
[hide private]
[frames] | no frames]

Package encutils

source code

encutils - encoding detection collection for Python

encutils

A collection of helper functions to detect encodings of text files (like HTML, XHTML, XML, CSS, etc.) retrieved via HTTP, file or string.

getEncodingInfo is probably the main function of interest which uses other supplied functions itself and gathers all information together and supplies an EncodingInfo object with the following properties:

example:

>>> import encutils
>>> info = encutils.getEncodingInfo(url='http://cthedot.de/encutils/')

>>> print info  # = str(info)
utf-8

>>> info        # = repr(info)
<encutils.EncodingInfo object encoding='utf-8' mismatch=False at 0xb86d30>

>>> print info.logtext
HTTP media_type: text/html
HTTP encoding: utf-8
HTML META media_type: text/html
HTML META encoding: utf-8
Encoding (probably): utf-8 (Mismatch: False)

references

XML

RFC 3023 (http://www.ietf.org/rfc/rfc3023.txt)

easier explained in
HTML
http://www.w3.org/TR/REC-html40/charset.html#h-5.2.2

TODO


Author: Christof Hoeke, see http://cthedot.de/encutils/

Copyright: 2005-2008: Christof Hoeke

License:

encutils has a dual-license, please choose whatever you prefer:

This file is part of encutils.

encutils is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.

encutils is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License along with encutils. If not, see <http://www.gnu.org/licenses/>.

Version: 0.8.3 $Id: __init__.py 1138 2008-03-15 18:24:46Z cthedot $

Submodules [hide private]

Classes [hide private]
  _MetaHTMLParser
parses given data for <meta http-equiv="content-type">
  EncodingInfo
All encoding related information, returned by getEncodingInfo
Functions [hide private]
 
buildlog(logname='encutils', level='INFO', stream=sys.stderr, filename=None, filemode='w', format='%(levelname)s\t%(message)s')
helper to build a basic log
source code
 
_getTextTypeByMediaType(media_type, log=None)
returns type as defined by constants above
source code
 
_getTextType(text, log=None)
checks if given text is XML (naive test!) used if no content-type given
source code
 
encodingByMediaType(media_type, log=None)
Returns a default encoding for the given media_type.
source code
 
getHTTPInfo(response, log=None)
Returns (media_type, encoding) information from the response' Content-Type HTTP header.
source code
 
getMetaInfo(text, log=None)
Returns (media_type, encoding) information from (first) X/HTML Content-Type <meta> element if available.
source code
 
detectXMLEncoding(fp, log=None, includeDefault=True)
Attempts to detect the character encoding of the xml file given by a file object fp.
source code
 
tryEncodings(text, log=None)
If installed uses chardet http://chardet.feedparser.org/ to detect encoding, else tries different encodings on text and returns the one that does not raise an exception which is not very advanced or may be totally wrong.
source code
 
getEncodingInfo(response=None, text=u'', log=None, url=None)
Finds all encoding related information in given text.
source code
Variables [hide private]
  __author__ = 'Christof Hoeke'
  _XML_APPLICATION_TYPE = 0
  _XML_TEXT_TYPE = 1
  _HTML_TEXT_TYPE = 2
  _TEXT_TYPE = 3
  _TEXT_UTF8 = 5
  _OTHER_TYPE = 4

Imports: cgi, HTMLParser, httplib, re, StringIO, sys, types, urllib


Function Details [hide private]

buildlog(logname='encutils', level='INFO', stream=sys.stderr, filename=None, filemode='w', format='%(levelname)s\t%(message)s')

source code 

helper to build a basic log

  • if filename is given returns a log logging to filename with mode filemode
  • else uses a log streaming to stream which defaults to sys.stderr
  • level defines the level of the log
  • format defines the formatter format of the log

returns a log with the name logname

encodingByMediaType(media_type, log=None)

source code 

Returns a default encoding for the given media_type. For example 'utf-8' for media_type='application/xml'.

Refers to RFC 3023 and HTTP MIME specification.

If no default encoding is available returns None.

getHTTPInfo(response, log=None)

source code 
Returns (media_type, encoding) information from the response' Content-Type HTTP header. (Case of headers is ignored.) May be (None, None) e.g. if no Content-Type header is available.

getMetaInfo(text, log=None)

source code 

Returns (media_type, encoding) information from (first) X/HTML Content-Type <meta> element if available.

Normally in X/HTML:
<meta http-equiv="Content-Type" content="media_type; charset=encoding"/>

detectXMLEncoding(fp, log=None, includeDefault=True)

source code 

Attempts to detect the character encoding of the xml file given by a file object fp. fp must not be a codec wrapped file object! fp may also be a string or unicode string

The return value can be:
  • if detection of the BOM succeeds, the codec name of the corresponding unicode charset is returned
  • if BOM detection fails, the xml declaration is searched for the encoding attribute and its value returned. the "<" character has to be the very first in the file then (it's xml standard after all).
  • if BOM and xml declaration fail, utf-8 is returned according to XML 1.0.

Based on a recipe by Lars Tiede: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/363841 which itself is based on Paul Prescotts recipe: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52257

tryEncodings(text, log=None)

source code 

If installed uses chardet http://chardet.feedparser.org/ to detect encoding, else tries different encodings on text and returns the one that does not raise an exception which is not very advanced or may be totally wrong.

Returns working encoding or None if no encoding does work at all.

The returned encoding might nevertheless be not the one intended by the author as it is only checked if the text might be encoded in that encoding. Some texts might be working in "iso-8859-1" and "windows-1252" and "ascii" and "utf-8" and ...

getEncodingInfo(response=None, text=u'', log=None, url=None)

source code 

Finds all encoding related information in given text. Uses information in headers of supplied HTTPResponse, possible XML declaration and X/HTML <meta> elements. text will mostly be HTML or XML.

Parameters
  • response: HTTP response object, e.g. urllib.urlopen('url')
  • text: to guess encoding for, might include XML prolog with encoding pseudo attribute or HTML meta element
  • log: an optional logging logger to which messages may go, if no log given all log messages are available from resulting EncodingInfo

May also simply be called with getEncodingInfo(url='URL') which fetches the url and all needed information.

Returns instance of EncodingInfo.

How the resulting encoding is retrieved

XML

RFC 3023 states if media type given in the Content-Type HTTP header is application/xml, application/xml-dtd, application/xml-external-parsed-entity, or any one of the subtypes of application/xml such as application/atom+xml or application/rss+xml etc then the character encoding is determined in this order:

1. the encoding given in the charset parameter of the Content-Type HTTP header, or 2. the encoding given in the encoding attribute of the XML declaration within the document, or 3. utf-8.

Mismatch possibilities:
  • HTTP + XMLdecla
  • HTTP + HTMLmeta
application/xhtml+xml ?
XMLdecla + HTMLmeta

If the media type given in the Content-Type HTTP header is text/xml, text/xml-external-parsed-entity, or a subtype like text/Anything+xml, the encoding attribute of the XML declaration is ignored completely and the character encoding is determined in the order: 1. the encoding given in the charset parameter of the Content-Type HTTP header, or 2. ascii.

Mismatch possibilities:
  • HTTP + XMLdecla
  • HTTP + HTMLmeta
text/xhtml+xml
XMLdecla + HTMLmeta

HTML

For HTML served as text/html:
http://www.w3.org/TR/REC-html40/charset.html#h-5.2.2
  1. An HTTP "charset" parameter in a "Content-Type" field. (maybe defaults to ISO-8859-1, but should not assume this)
  2. A META declaration with "http-equiv" set to "Content-Type" and a value set for "charset".
  3. The charset attribute set on an element that designates an external resource. (NOT IMPLEMENTED HERE YET)
Mismatch possibilities:
  • HTTP + HTMLmeta

TEXT

For most text/* types the encoding will be reported as iso-8859-1. Exceptions are XML formats send as text/* mime type (see above) and text/css which has a default encoding of UTF-8.