gpt4 book ai didi

python 3 无法将字节连接到列表的 str

转载 作者:太空宇宙 更新时间:2023-11-04 08:45:47 24 4
gpt4 key购买 nike

我正在尝试运行以下代码块

import json
import textProcess as tp

review = open('../inres_review.json')
vocabulary = open('../vocabulary.txt','w+')
label = open('../label.txt','w+')
data = open('../data.txt','w+')

voc = []
revs = []
lab = []
dat = []
i=1
for line in review:
jre = json.loads(line)
jstar = jre['stars']
text = jre['text']
lab.append(jstar)
ws = tp.removeStopPunc(text)
revs.append(ws)
voc += ws
i += 1

for i in lab:
label.write(str(i)+"\n")
print ("label created successfully!")

voc = list(set(voc))
print (len(voc))
print (type(i))
for i in voc:
vocabulary.write(i.encode('UTF-8')+"\n")
print ("Vocabulary created successfully!")

for revid, rev in enumerate(revs):
dat.append({})
for w in rev:
if w in voca:
k = voca.index(w)+1
if k not in dat[revid]:
dat[revid][k] = 1
else:
dat[revid][k] += 1
print (len(revs))


for revid, rev in enumerate(dat):
for k,v in rev.iteritems():
s = str(revid+1)+' '+str(k)+' '+str(v)+'\n'
data.write(s)
print ("successfully create data")


review.close()
vocabulary.close()
label.close()
data.close()

但是,无论我实现什么更改,我都会收到以下错误。任何人都可以指出这里有什么问题吗?

TypeError                                 Traceback (most recent call last)
<ipython-input-18-21a3dc9eb8ad> in <module>()
33 print (type(i))
34 for i in bvoca:
---> 35 vocabulary.write(i.encode('UTF-8')+"\n")
36 print ("successfully create vocabulary!")
37

TypeError: can't concat bytes to str

感谢任何帮助!

最佳答案

encode 返回bytes,因此您还需要将'\n' 转换为bytes:

i.encode('UTF-8') + b"\n"

关于python 3 无法将字节连接到列表的 str,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40740150/

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