[英]TypeError: write() argument must be str, not bytes (Python 3 vs Python 2 )
[英]Python - TypeError: write() argument must be str, not bytes
我收到了来自 python 的错误消息。 它是从牛津在线词典中提取音标的代码。
回溯(最近一次调用):文件“C:\\Download\\Oxford_PhoneticSymbol\\Oxford_PhoneticSymbol.py”,第 24 行,在 fw.write((result + "\\n").encode("utf-8")) 类型错误: write() 参数必须是 str,而不是字节
原始来源来自; https://my.oschina.net/sfshine/blog/3076588
# -*- coding: UTF-8 -*-
import requests
import time
from bs4 import BeautifulSoup
f = open('./words.txt')
fw = open('./result.txt','a')
line = f.readline()
index = 0
while line:
index = index+1
url = "https://www.oxfordlearnersdictionaries.com/definition/english/" + line.strip()
print(str(index) + ":" + url)
wbdata = requests.get(url,headers={'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.75 Safari/537.36'}).text
soup = BeautifulSoup(wbdata,'html.parser')
news_titles = soup.select("span.pron-g > span.phon")
# print(news_titles)
result = ''
for n in news_titles:
title = n.get_text()
if 'NAmE' in title:
result += '['+title.replace('NAmE','').replace('//','') + ']'
print(result)
fw.write((result + "\n").encode("utf-8"))
line = f.readline()
time.sleep(0.1)
fw.close()
f.close()
根据需要,我已将两个 txt 文件放在同一目录中。 我在words.txt中填了几个字,把result.txt设为空白,但我得到了错误。
(words.txt, saved as UTF-8)
source
technic
resource
power
box
created
computer
charged
learned
任何想法如何解决这个问题?
将下载的页面保存到文件时出现此错误的解决方法:
类型错误:write() 参数必须是 str,而不是字节
是:
fw = open('./result.txt','wb')
二进制的“b”有所不同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.