Nidhi Sirohi Nidhi Sirohi - 8 months ago 73
Python Question

python 3 can't concat bytes to str for a list

I have the following chunk of code that I'm trying to run

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 = []
for line in review:
jre = json.loads(line)
jstar = jre['stars']
text = jre['text']
ws = tp.removeStopPunc(text)
voc += ws
i += 1

for i in lab:
print ("label created successfully!")

voc = list(set(voc))
print (len(voc))
print (type(i))
for i in voc:
print ("Vocabulary created successfully!")

However, no matter what I changes I implement I am getting the following error. Can anyone please point out what's wrong here?

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!")

TypeError: can't concat bytes to str

Answer Source

encode returns bytes, so you need to convert '\n' to bytes as well:

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