推荐学习书目
› 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
oddcc
V2EX  ›  Python

关于 Pycharm 非常奇怪的问题, 麻烦进来看下

  •  
  •   oddcc · Dec 28, 2016 · 3347 views
    This topic created in 3565 days ago, the information mentioned may be changed or developed.

    一个很简单的脚本, 使用os.system()执行了一句 Java 语句, 这句 Java 的作用就是解析 pdf 文件, 输出文本到一个 csv 文件.

    问题是这个脚本如果在 PyCharm 里跑的话, 写入的编码就是 ASCII, 打开中文就是问号; 如果在终端直接运行, 写入的编码就是 UTF-8, 中文显示一切正常

    PyCharm 中有关 encoding 的设置都是 utf-8.

    代码如下

    # coding=utf-8
    import os
    import chardet
    
    
    cmd = 'java -jar ~/tabula.jar ~/80032035 陈勇.pdf -p all -n -o pdf.csv'
    os.system(cmd)
    f = open("pdf.csv", 'rb')
    for l in f.readlines():   # 这两句检查文本编码方式
        print chardet.detect(l)
    

    在 PyCharm 中运行的话, pdf.csv 是这样的:

    {'confidence': 1.0, 'encoding': 'ascii'} 输出显示编码方式是 ASCII

    如果在终端运行的话, pdf.csv 是这样的:

    {'confidence': 0.99, 'encoding': 'utf-8'} 输出显示编码方式是 UTF-8

    现在不知道问题出在哪里了...求教

    5 replies  •  2016-12-28 16:26:46 +08:00
    bazingaterry
        1
    bazingaterry  
       Dec 28, 2016 via iPhone
    open 那里指定一下 encoding
    Sylv
        2
    Sylv  
       Dec 28, 2016   ❤️ 1
    感觉可能是 PyCharm 和终端的环境变量不同导致的问题,尝试分别在两处运行以下代码看看环境变量有什么不同:
    import os
    print os.environ
    wwqgtxx
        3
    wwqgtxx  
       Dec 28, 2016 via iPhone
    你用 notepad++看看两次生成的 csv 文件的具体编码
    有可能是你调用的那个 jar 库根据环境变量生成了不同的编码格式的 csv 文件
    kokutou
        4
    kokutou  
       Dec 28, 2016 via Android
    cmd 。。。。
    在执行你的 cmd 之前,执行一下 chcp 65001 切换 Windows 默认代码页从 cp936 到 utf-8 。。。
    oddcc
        5
    oddcc  
    OP
       Dec 28, 2016
    @Sylv 谢谢, 您的方法是对的

    对比了之后发现, PyCharm 的环境变量中是 'LC_CTYPE': 'en_US.UTF-8'
    终端中'LC_CTYPE': 'UTF-8'

    在 PyCharm 中设置了环境变量之后就 OK 了, 非常感谢
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   833 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 22:06 · PVG 06:06 · LAX 15:06 · JFK 18:06
    ♥ Do have faith in what you're doing.