Python - TypeError: write() argument must be str, not bytes
Python - 类型错误:write()参数必须是str而不是bytes。
Python - TypeError: write() argument must be str, not bytes
Python - 类型错误:write()参数必须是str而不是bytes。
我从Python收到了一个错误信息。这是一个从牛津在线词典中提取音标符号的代码。
Traceback (most recent call last): File
\"C:\\Download\\Oxford_PhoneticSymbol\\Oxford_PhoneticSymbol.py\", line 24,
in
fw.write((result + \"\\n\").encode(\"utf-8\")) TypeError: write() argument must be str, not bytes
原始来源: 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 + " ").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
有什么想法如何修复这个问题吗?
admin 更改状态以发布 2023年5月24日