---
title: "自动检测文件编码"
author: "john2007"
date: "2009-12-31T11:19:48Z"
tags: []
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2009-12-31T11:19:48Z"
id: 560312
url: "https://john2007.iteye.com/blog/560312"
---

对于抓取的网页处理时，我们往往要判断它的字符编码，今天发现了python的一个自动判断编码的lib，特与众分享.

名称：chardet

介绍：Character encoding auto-detection in Python 2 and 3. As smart as your browser. Open source.

 

下载地址：

[http://pypi.python.org/pypi/chardet/1.0.1](http://pypi.python.org/pypi/chardet/1.0.1)

文档地址：

[http://chardet.feedparser.org/docs/index.html](http://chardet.feedparser.org/docs/index.html)

 

文档目录：

 

 

- [Frequently asked questions](http://chardet.feedparser.org/docs/faq.html)
  
  - [What is character encoding?](http://chardet.feedparser.org/docs/faq.html#faq.intro)
  - [What is character encoding auto-detection?](http://chardet.feedparser.org/docs/faq.html#faq.what)
  - [Isn’t that impossible?](http://chardet.feedparser.org/docs/faq.html#faq.impossible)
  - [Who wrote this detection algorithm?](http://chardet.feedparser.org/docs/faq.html#faq.who)
  - [Yippie! Screw the standards, I’ll just auto-detect everything!](http://chardet.feedparser.org/docs/faq.html#faq.yippie)
  - [Why bother with auto-detection if it’s slow, inaccurate, and non-standard?](http://chardet.feedparser.org/docs/faq.html#faq.why)
- [Supported encodings](http://chardet.feedparser.org/docs/supported-encodings.html)
- [Usage](http://chardet.feedparser.org/docs/usage.html)
  
  - [Basic usage](http://chardet.feedparser.org/docs/usage.html#usage.basic)
  - [Advanced usage](http://chardet.feedparser.org/docs/usage.html#usage.advanced)
- [How it works](http://chardet.feedparser.org/docs/how-it-works.html)
  
  - [UTF-n with a BOM](http://chardet.feedparser.org/docs/how-it-works.html#how.bom)
  - [Escaped encodings](http://chardet.feedparser.org/docs/how-it-works.html#how.esc)
  - [Multi-byte encodings](http://chardet.feedparser.org/docs/how-it-works.html#how.mb)
  - [Single-byte encodings](http://chardet.feedparser.org/docs/how-it-works.html#how.sb)
  - [windows-1252](http://chardet.feedparser.org/docs/how-it-works.html#how.windows1252)
- [Revision history](http://chardet.feedparser.org/docs/history.html)
- [Terms of use](http://chardet.feedparser.org/docs/license.html)

basic usage：

```
>>> import urllib
>>> rawdata = urllib.urlopen('http://yahoo.co.jp/').read()
```

```
>>> import chardet
>>> chardet.detect(rawdata)
```

```

{'encoding': 'EUC-JP', 'confidence': 0.99}
```