虽然我正在编译我收到此错误。我已经搜索但没有解决方案不起作用
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
在这里each["title"].encode("ascii", "ignore")
你正在生成一个bytes
类型的对象列表,并在这里"\n".join(titles)
你试图join
他们在str
ing。连接bytes
对象和字符串是不可能的,所以你得到一个错误。
如果您想在加入后生成bytes
对象,请执行以下操作:
"\n".join(titles)
但是,您需要以二进制模式打开文件。否则,只是不要encode
你的数据。