小例子:list1=[1,'two','three',4]
print(' '.join(list1))
以为会打印 1 two three 4
结果报了错
Traceback (most recent call last):
File "<pyshell#27>", line 1, in <module>
print(" ".join(list1))
TypeError: sequence item 0: expected str instance, int found
上网查了资料,说list包含数字,不能直接转化成字符串。
解决办法:print(" ".join('%s' %id for id in list1))
即遍历list的元素,把他转化成字符串。这样就能成功输出1 two three 4结果了。
我的代码:
#output = open(outp, 'w', encoding='utf-8') output = open(outp, 'wt', encoding='utf-8')#使用 “t” 类型打开文件,字符串的形式 wiki = WikiCorpus(inp, lemmatize=False, dictionary={}) for text in wiki.get_texts(): #output.write(b' '.join(text).decode('utf-8') + '\n') output.write( " ".join('%s' %id for id in text) + '\n')#遍历list的元素,把每个元素转化成字符串。 #output.write('\n') i = i + 1 if i % 10000 == 0: logger.info('Saved ' + str(i) + ' articles') output.close()
注意:
b' '.join(text) 是以bytes(字节)的形式添加字符串,再“.decode('utf-8') ”,将bytes(字节)转为str(字符串)。
采用直接用str字符串的形式。
" ".join('%s' %id for id in text) #遍历list的元素,把每个元素转化成字符串。