我收到了来自python的错误消息。 这是从牛津在线词典中提取语音符号的代码。
回溯(最近通话最近):文件 “ C:\ Download \ Oxford_PhoneticSymbol \ Oxford_PhoneticSymbol.py”,第24行, 在 fw.write((result +“ \ n”)。encode(“ utf-8”))TypeError: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
任何想法如何解决?
答案 0 :(得分:2)
将下载的页面保存到文件时针对此错误的解决方案:
TypeError:write()参数必须为str,而不是字节
是:
fw = open('./result.txt','wb')
“ b”代表二进制文件。