我正在编译时出现类型错误

问题描述 投票:0回答:1

虽然我正在编译我收到此错误。我已经搜索但没有解决方案不起作用

import requests
import tqdm

BASE_URL="http://www.buzzfeed.com/api/v2/feeds/index"


with open("G:\clickbait-detector-master\data/clickbait.txt", "a+") as outfile:

    for page in tqdm.tqdm(range(0, 30)):
        response = requests.get(BASE_URL, { "p": page }).json()
        titles = [each["title"].encode("ascii", "ignore") for each in response["buzzes"]]
        outfile.write("\n" + "\n".join(titles))

编译后我得到输出

TypeError                                 Traceback (most recent call last)
<ipython-input-5-5231e1171fef> in <module>()
     11         response = requests.get(BASE_URL, { b"p": page }).json()
     12         titles = [each["title"].encode("ascii", "ignore") for each in response["buzzes"]]
---> 13         outfile.write("\n" + "\n".join(titles))

TypeError: sequence item 0: expected str instance, bytes found
python-3.x
1个回答
0
投票

在这里each["title"].encode("ascii", "ignore")你正在生成一个bytes类型的对象列表,并在这里"\n".join(titles)你试图join他们在string。连接bytes对象和字符串是不可能的,所以你得到一个错误。

如果您想在加入后生成bytes对象,请执行以下操作:

"\n".join(titles)

但是,您需要以二进制模式打开文件。否则,只是不要encode你的数据。

© www.soinside.com 2019 - 2024. All rights reserved.