【问题标题】:Some Decoding Issue With String in PythonPython中字符串的一些解码问题
【发布时间】:2015-06-27 13:30:47
【问题描述】:

我正在尝试将来自 Google 的 HTML 代码字符串写入 Python 3.4 中的文件

#coding=utf-8
try:
    from urllib.request import Request, urlopen  # Python 3
except:
    from urllib2 import Request, urlopen  # Python 2

useragent = 'Mozilla/5.0 (Windows NT 6.3; rv:36.0) Gecko/20100101 Firefox/36.0'

#Generate URL
url = 'https://www.google.com.tw/search?q='
query = str(input('Google It! :'))
full_url = url+query


#Request Data
data = Request(full_url)
data.add_header('User-Agent', useragent)
dataRequested = urlopen(data).read()
dataRequested = str(dataRequested.decode('utf-8'))


print(dataRequested)

#Write Data Into File
file = open('Google - '+query+'.html', 'w')
file.write(dataRequested)

它可以正确打印字符串, 但是当它写入文件时, 它会显示

file.write(dataRequested)
UnicodeEncodeError: 'cp950' codec can't encode character '\u200e' in position 97658: illegal multibyte sequence

我试图改变解码方式,但它不起作用。 我也尝试替换\u200e,但它会出现更多的编码字符错误。

【问题讨论】:

    标签: python python-3.x unicode unicode-string


    【解决方案1】:

    你的问题是

    dataRequested = str(dataRequested.decode('utf-8'))

    是否有理由将解码后的 UTF-8 转换为字符串?但这还不是全部。当您从 Internet 获取字符串时,它应该被解码,但是当您保存字符串时,它应该被编码。有些人不明白。他们要么解码要么编码。这样不行。

    我稍微修改了你的代码。它在 Python2.7 和 Python3.4 上都适用于我。

    dataRequested = dataRequested.decode('utf-8')
    
    
    print(dataRequested)
    
    #Write Data Into File
    file = open('Google - '+query+'.html', 'wb')
    file.write(dataRequested.encode('utf-8'))
    

    【讨论】:

    • 加油!我只是拼错了几个字。
    • 啊哈。我现在明白了。谢谢。对于我的生活,我看不出这就是你的意思! “获取字符串”和“不获取”的并列看起来令人困惑。对不起。读起来会更好,因为有些人不明白。感谢修复。
    猜你喜欢
    • 2011-01-24
    • 1970-01-01
    • 2019-05-25
    • 2017-10-05
    • 2011-07-14
    • 2016-10-31
    • 1970-01-01
    • 2014-01-08
    • 2012-02-22
    相关资源
    最近更新 更多