V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
ekoeko
V2EX  ›  Python

python3 处理 gbk 编码文件的问题

  •  
  •   ekoeko · Jun 5, 2019 · 3018 views
    This topic created in 2524 days ago, the information mentioned may be changed or developed.

    各位大佬好,请教一个问题,我有一个源文件是 gbk 编码的,现在要修改其中的内容。内容是有规范的,比如第一位到第三位是序号。但是这个站位是按照字节来算,比如中文字符算 2 位,英文字符算 1 位,我把文件内容当成字符串读到文件之后,这个字符站位默认都是一位,所以我无法按照规范定位到应该修改的位置。

    想了半天查了很多资料,好像相关问题的资料很少,求各位大佬帮帮忙。

    4 replies    2019-06-06 12:54:48 +08:00
    vinceguo
        1
    vinceguo  
       Jun 5, 2019 via Android   ❤️ 1
    读取文件的时候指定编码,试试
    fp = open('xxx.txt', encoding='gb18030')
    ysc3839
        2
    ysc3839  
       Jun 5, 2019 via Android   ❤️ 1
    你需要计算的时候把 string encode 成 gbk bytes 再算长度就行了。
    ekoeko
        3
    ekoeko  
    OP
       Jun 5, 2019
    @ysc3839 感谢大佬,已经成功
    ps1aniuge
        4
    ps1aniuge  
       Jun 6, 2019
    用 powershell 没有这样的问题,或者说可以避过。

    中英文长度都是 1 字符,不按字节统计。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   805 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 35ms · UTC 19:44 · PVG 03:44 · LAX 12:44 · JFK 15:44
    ♥ Do have faith in what you're doing.