gpt4 book ai didi

Python - TypeError : write() argument must be str, 不是字节

转载 作者:行者123 更新时间:2023-12-04 02:41:33 26 4
gpt4 key购买 nike

我收到了来自 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 + "\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

知道如何解决这个问题吗?

最佳答案

将下载的页面保存到文件时出现此错误的解决方法:

TypeError: write() argument must be str, not bytes



是:
fw = open('./result.txt','wb')

二进制的“b”有所不同。

关于Python - TypeError : write() argument must be str, 不是字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59173158/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com