鱼C论坛

 找回密码
 立即注册
查看: 721|回复: 1

编码解码问题

[复制链接]
发表于 2018-7-19 13:36:55 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
import urllib.request
import chardet

def save(urls):
    i=1
    for name in urls:
        response=urllib.request.urlopen(name)
        html=response.read()
        str1=chardet.detect(html)['encoding']
        #print('该网页使用的编码是:%s'%str1)
        if str1=='GB2312':
            str1='GBK'
        elif str1=='UTF-8-SIG':
            str1='UTF-8'
        #ignore解码时忽略非法字符
        html=html.decode(str1,'ignore')
        #open的时候带一个encoding参数
        f=open("d:\\test\\url_%d.txt"%i,'w',encoding=str1)
        f.write(html)
        f.close()
        i+=1

def main():
    f=open("d:\\test\\urls.txt")
    urls=[]
    while True:
        url=f.readline()
        url=url.strip('\n')
        if url=='':
            break
        urls.append(url)
        
    f.close()
    save(urls)

if __name__=='__main__':
    main()

   
问题1:18行,open()里面加不加encoding=str1得到的文件内容都是一样的,这是为什么?
问题2:UTF-8-SIG编码怎么解码?可以直接用UTF-8解码吗?
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2018-7-19 19:20:25 | 显示全部楼层
??怎么没人来
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-12-31 21:31

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表