python中英文字符和中文字符_如何在文件中同时写入中英文字符(Python3)?

我写了一个脚本来抓取YouTube播放列表页面的标题

根据print语句,一切正常,直到我尝试将标题写入文本文件,这时我得到“UnicodeEncodeError:'charmap'codec无法对字符进行适当的编码…”

我尝试在打开文件时添加“encoding='utf8'”,虽然这样可以修复错误,但所有的汉字都被随机的、乱七八糟的字符所取代

我还尝试用'replace'对输出字符串进行编码,然后对其进行解码,但这也只是将所有特殊字符替换为问号

这是我的代码:from bs4 import BeautifulSoup as BS

import urllib.request

import re

playlist_url = input("gib nem: ")

with urllib.request.urlopen(playlist_url) as response:

playlist = response.read().decode('utf-8')

soup = BS(playlist, "lxml")

title_attrs = soup.find_all(attrs={"data-title":re.compile(r".*")})

titles = [tag["data-title"] for tag in title_attrs]

titles_str = '\n'.join(titles)#.encode('cp1252','replace').decode('cp1252')

print(titles_str)

with open("playListNames.txt", "a") as f:

f.write(titles_str)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值