Hexo

凡事预则立,不预则废


  • Home

  • Tags

  • Archives

  • Navigation

  • Search

Python——判断未知源的编码类型

有时候遇到一个文件,而我们并不知道它是什么编码方式编码的,本文给出了一些判断未知文件编码方式的方法


使用chardet包


在程序中判断

  • 安装Chardet包

    1
    pip install chardet
  • 使用Chardet包做判断

    1
    2
    3
    4
    5
    6
    import urllib
    rawdata = urllib.urlopen('http://yahoo.co.jp/').read()
    import chardet
    print chardet.detect(rawdata)
    # Output:
    {'confidence': 0.99, 'language': '', 'encoding': 'utf-8'}

更多高级使用方法可参考chardet文档


直接使用命令判断

  • 安装chardetect工具

    1
    pip install chardet
  • 使用chardetect命令

    1
    2
    3
    4
    # 检测test.txt文件的编码方式
    chardetect test.txt
    # Output:
    test-chardetect.txt: ascii with confidence 1.0

Python——反编译(Disassemble)与字节码(Bytecode)

为了知道Python代码底层都做了哪些操作,我们常常需要反编译Python代码以获得Python的字节码
我们可以获得: classes, methods, functions, or code 的字节码


获取字节码的方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# 比较`[]`和`list()`两者的不同
from dis import dis

# test case 1
dis("[]")
# Output:
1 0 BUILD_LIST 0
2 RETURN_VALUE

# test case 2
dis("list()")
# Output:
1 0 LOAD_NAME 0 (list)
2 CALL_FUNCTION 0
4 RETURN_VALUE

**由上述输出可知,`list()` 比 `[]` 会多执行一行字节码`LODA_NAME`**
1…270271272…352
San Ye

San Ye

Stay Hungry. Stay Foolish.

704 posts
53 tags
© 2026 San Ye
Powered by Hexo
|
Theme — NexT.Gemini v5.1.4