编程进阶网 编程进阶网
首页
  • 计算机原理
  • 操作系统
  • 网络协议
  • 数据库原理
  • 面向对象
  • 设计原则
  • 设计模式
  • 系统架构
  • 性能优化
  • 编程原理
  • 方案设计
  • 稳定可靠
  • 工程运维
  • 基础认知
  • 线性结构
  • 树与哈希
  • 工业级实现
  • 算法思想
  • 实战与综合
  • 算法题考核
  • C语言入门
  • C综合案例
  • C专栏博客
  • C标准集库
  • C++入门教程
  • C++综合案例
  • C++专栏博客
  • C++开发技巧
  • Java入门教程
  • Java综合案例
  • Java专栏博客
  • Go入门教程
  • Go综合案例
  • Go专栏博客
  • Go开发技巧
  • JavaScript入门
  • JavaScript高级
  • Android库解读
  • Android专栏
  • Android智能硬件
  • iOS ObjC入门
  • iOS Swift入门
  • iOS入门精通
  • Web之Html手册
  • Web之TypeScript
  • Web之Vue高级进阶
  • Linux之QML入门
  • Linux之QT核心库
  • Linux实践开发
  • Python教程
  • Shell&Bash教程
  • 工具脚本
  • 自动化脚本
  • 质量保障
  • 产品思考
  • 软实力
  • 开发流程
  • Git应用
  • 技术模版
  • 技术规范
  • Markdown
  • Mermaid
  • 开源协议
  • JSON工具
  • 文本工具
  • 图片处理
  • 文档转化
  • 代码压缩
  • 关于我
  • 自我精进
  • 职场管理
  • 职场面试
  • 心情杂货
  • 友情链接

杨充

专注编程 · 终身学习者
首页
  • 计算机原理
  • 操作系统
  • 网络协议
  • 数据库原理
  • 面向对象
  • 设计原则
  • 设计模式
  • 系统架构
  • 性能优化
  • 编程原理
  • 方案设计
  • 稳定可靠
  • 工程运维
  • 基础认知
  • 线性结构
  • 树与哈希
  • 工业级实现
  • 算法思想
  • 实战与综合
  • 算法题考核
  • C语言入门
  • C综合案例
  • C专栏博客
  • C标准集库
  • C++入门教程
  • C++综合案例
  • C++专栏博客
  • C++开发技巧
  • Java入门教程
  • Java综合案例
  • Java专栏博客
  • Go入门教程
  • Go综合案例
  • Go专栏博客
  • Go开发技巧
  • JavaScript入门
  • JavaScript高级
  • Android库解读
  • Android专栏
  • Android智能硬件
  • iOS ObjC入门
  • iOS Swift入门
  • iOS入门精通
  • Web之Html手册
  • Web之TypeScript
  • Web之Vue高级进阶
  • Linux之QML入门
  • Linux之QT核心库
  • Linux实践开发
  • Python教程
  • Shell&Bash教程
  • 工具脚本
  • 自动化脚本
  • 质量保障
  • 产品思考
  • 软实力
  • 开发流程
  • Git应用
  • 技术模版
  • 技术规范
  • Markdown
  • Mermaid
  • 开源协议
  • JSON工具
  • 文本工具
  • 图片处理
  • 文档转化
  • 代码压缩
  • 关于我
  • 自我精进
  • 职场管理
  • 职场面试
  • 心情杂货
  • 友情链接
  • ScriptHub 脚本工具箱
  • Python

  • Shell-Bash

  • 工具脚本

    • 工具脚本速查
    • 哈希校验
    • Base64编码
    • AES加解密
    • RSA签名验签
    • JWT令牌
    • JSON与YAML
    • XML与CSV
    • 编码转义
      • 一、编码检测与转换
        • 1.1 chardet——自动检测文件编码
        • 1.2 Python encode/decode
      • 二、URL 编码 / HTML 转义
        • 2.1 URL 编码(百分号编码)
        • 2.2 HTML 实体转义
      • 三、Shell 编码转换
    • 图片转换
    • 文档转换
    • 批量重命名
    • 分割合并
    • 目录同步
    • 文件监控
    • 压缩归档
    • 文件去重
    • cURL速查
    • HTTP调试
    • 端口DNS
    • 抓包代理
  • ScriptHub
  • 工具脚本
杨充
2019-11-09
目录

编码转义

# 编码转义

自动检测编码(chardet)、URL 编码/解码、HTML 实体转义、Shell iconv 编码转换。

# 一、编码检测与转换

# 1.1 chardet——自动检测文件编码

pip install chardet
1
#!/usr/bin/env python3
"""自动检测编码并正确读取文件"""
import chardet

def read_file_smart(filepath):
    """智能读取——先检测编码,再解码"""
    with open(filepath, 'rb') as f:
        raw = f.read()

    result = chardet.detect(raw)
    encoding = result['encoding']
    confidence = result['confidence']

    print(f"检测编码: {encoding} (置信度: {confidence:.0%})")
    return raw.decode(encoding)

# ---- 示例 ----
text = read_file_smart('unknown_file.txt')
print(text[:200])

# ===== 批量转换文件编码 =====
def convert_encoding(input_path, output_path, to_encoding='utf-8'):
    with open(input_path, 'rb') as f:
        raw = f.read()
    detected = chardet.detect(raw)['encoding'] or 'gbk'
    with open(output_path, 'w', encoding=to_encoding) as f:
        f.write(raw.decode(detected))
    print(f"✅ {detected} → {to_encoding}: {output_path}")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

# 1.2 Python encode/decode

#!/usr/bin/env python3

# ---- 字符串与字节互转 ----
text = "你好"
utf8_bytes = text.encode('utf-8')     # b'\xe4\xbd\xa0\xe5\xa5\xbd'
gbk_bytes  = text.encode('gbk')       # b'\xc4\xe3\xba\xc3'

decoded = utf8_bytes.decode('utf-8')  # '你好'

# ---- 常见编码错误处理 ----
# 'ignore' 跳过、'replace' 用 � 替代
broken = b'\xc0\xaf'.decode('utf-8', errors='replace')  # '��'
safe   = b'\xc0\xaf'.decode('utf-8', errors='ignore')   # ''

# ---- 检测 BOM 头 ----
def has_bom(data):
    """检测 UTF-8/UTF-16 BOM"""
    if data.startswith(b'\xef\xbb\xbf'): return 'UTF-8-BOM'
    if data.startswith(b'\xff\xfe'):     return 'UTF-16-LE'
    if data.startswith(b'\xfe\xff'):     return 'UTF-16-BE'
    return None
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

# 二、URL 编码 / HTML 转义

# 2.1 URL 编码(百分号编码)

#!/usr/bin/env python3
from urllib.parse import quote, unquote, urlencode, parse_qs

# ---- 字符串 ↔ URL 编码 ----
text = "你好 world"
encoded = quote(text)            # '%E4%BD%A0%E5%A5%BD%20world'
decoded = unquote(encoded)       # '你好 world'

# 保留 / 不编码(用于路径)
quote("a/b c", safe='/')         # 'a/b%20c'

# ---- 查询参数编码 ----
params = {'q': '你好', 'page': '1'}
query = urlencode(params)        # 'q=%E4%BD%A0%E5%A5%BD&page=1'

# ---- 解析查询字符串 ----
parsed = parse_qs('q=%E4%BD%A0%E5%A5%BD&page=1')
print(parsed)                     # {'q': ['你好'], 'page': ['1']}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

# 2.2 HTML 实体转义

#!/usr/bin/env python3
import html

# ---- 转义——防 XSS ----
dangerous = '<script>alert("XSS")</script>'
safe = html.escape(dangerous)
print(safe)  # &lt;script&gt;alert(&quot;XSS&quot;)&lt;/script&gt;

# ---- 反转义 ----
original = html.unescape('&lt;div&gt;Hello&lt;/div&gt;')
print(original)  # <div>Hello</div>
1
2
3
4
5
6
7
8
9
10
11

# 三、Shell 编码转换

#!/bin/bash

# ===== iconv——编码转换 =====
iconv -f GBK -t UTF-8 gbk_file.txt > utf8_file.txt

# ===== 检测文件编码 =====
file -I unknown.txt                    # 显示 charset
# 输出:unknown.txt: text/plain; charset=utf-8

# ===== 批量转换目录下所有文件编码 =====
for f in *.txt; do
    iconv -f GBK -t UTF-8 "$f" -o "${f%.txt}_utf8.txt"
done

# ===== URL 编码/解码 =====
# 编码
python3 -c "import urllib.parse; print(urllib.parse.quote('你好世界'))"
# 解码
python3 -c "import urllib.parse; print(urllib.parse.unquote('%E4%BD%A0%E5%A5%BD'))"

# ===== HTML 转义 =====
python3 -c "import html; print(html.escape('<script>'))"
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#工具#格式
上次更新: 2026/06/17, 12:47:39
XML与CSV
图片转换

← XML与CSV 图片转换→

最近更新
01
信号崩溃快速排查
06-15
02
CoreDump破案
06-15
03
perf火焰图实战
06-15
更多文章>
Theme by Vdoing | Copyright © 2019-2026 杨充 | MIT License | 桂ICP备2024034950号 | 桂公网安备45142202000030
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式