簡體   English   中英

Python - 類型錯誤:write() 參數必須是 str,而不是字節

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM