用for循环处理pandas.df时,通常会遇到错误。当错误被删除后,我将不得不从数据帧的开头重新启动for循环。如何从错误位置启动for循环,避免重复运行。 例如:
senti = []
for i in dfs['ssentence']:
senti.append(get_baidu_senti(i))
在上面的代码中,我试图通过api进行情感分析,并将其存储到一个列表中,但是api只输入GBK格式,而我的数据是utf-8编码的,所以通常会遇到如下错误:
UnicodeEncodeError: 'gbk' codec can't encode character '\u30fb' in position 14: illegal multibyte sequence
因此,我必须手动删除像'\u30fb'这样的特定项,并重新启动for循环。此时,列表“senti”已经包含了太多的数据,所以我不想放弃它们。如何改进for循环
如果您的API需要编码到GBK,那么只需使用
'strict'
(默认值)以外的错误处理程序编码到该编解码器'ignore'
将删除任何无法编码为GBK的代码点:参见Error Handlers section of Python's ^{} documentation
如果需要传入字符串,但只传入可以安全编码为GBK的字符串,那么我将创建一个适合^{} method 的翻译映射:
InvalidForEncodingMap
类在查找代码点时延迟地创建条目,因此只处理数据中实际存在的代码点。我仍然会保留map实例以供重用如果您需要多次使用它,那么它构建的缓存可以这样重用相关问题 更多 >
编程相关推荐