Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/358.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 类型错误:can';t concat str到字节。列表到txt文件_Python_Twitter_Utf 8_Typeerror - Fatal编程技术网

Python 类型错误:can';t concat str到字节。列表到txt文件

Python 类型错误:can';t concat str到字节。列表到txt文件,python,twitter,utf-8,typeerror,Python,Twitter,Utf 8,Typeerror,我得到TypeError:当我试图将单词列表写入txt文件时,无法将str转换为字节 下面是书上的内容,它返回了TypeError,然后我尝试了不同的方法,结果成功了 # Error Code f = open('words.txt', 'w') for word in stemmed: try: f.write(word.encode('utf-8') + '\n') except UnicodeEncodeError, e: print 'En

我得到
TypeError:当我试图将单词列表写入txt文件时,无法将str转换为字节

下面是书上的内容,它返回了
TypeError
,然后我尝试了不同的方法,结果成功了

# Error Code
f = open('words.txt', 'w')
for word in stemmed:
    try:
        f.write(word.encode('utf-8') + '\n')
    except UnicodeEncodeError, e:
        print 'Enconding error ' + word + '\n'
f.close()

# Working Code
f= open('word.txt','w',encoding= 'utf-8')
for word in stemmed:
    try:
        f.write(word+'\n')
    except UnicodeEncodeError as e:
        print('Encoding Error' + word + '\n')
f.close()
两种代码之间的区别是什么? 似乎
#工作代码
将单词列表保存到
txt
文件中,但不打印任何编码错误


谢谢

错误代码,代码
word.encode()
的结果是一个类似字节的对象,因此,您不能将str和bytes合并。 工作代码:
单词和“\n”在放入txt文件之前已经进行了编码。

第一个片段(本书中的片段)似乎是为Python 2编写的。 在Python2中,字节字符串(type
str
)和Unicode字符串(type
Unicode
)可以混合使用——有时有效,有时引发Unicode错误,有时产生垃圾文本(“mojibake”)

但是,显然您正在运行Python3(这很好!),其中两种字符串类型不兼容:不能混合使用字节字符串(type
bytes
)和Unicode字符串(type
str

“工作代码”片段在我看来很好,不需要做任何更改(尽管使用
with
语句打开文件会很好)。 它不会产生任何UnicodeError,因为很少有UTF-8编码失败的情况。 如果有错误,将由
except
子句处理

可能不需要完全理解第一个代码段失败的原因。 抛开“错误代码”,试着找一本涵盖Python3的最新Python书籍。
Python 2很快就要停产了,如果您是一名新的Python学习者,您不必为此烦恼。

如何修复错误代码才能正常工作?工作代码不返回任何错误,但不确定它是否真的执行了UnicodeCodeerror(UnicodeCodeerror除外)作为e:#错误代码f=open('words.txt','wb')对于词干中的单词:try:f.write(word.encode('utf-8')+b'\n'),但UnicodeCodeeCodeerror除外,e:print'encoding error'+word+'\n'f.close()
@goudan为什么不编辑您的答案以包含这段代码?作为一个评论,它几乎是不可读的。