Python 3中unicode函数使用报错,如何正确导入并使用?
问题原因与解决方法
1. 报错根源
unicode()是Python 2的内置函数,用于将对象转换为Unicode字符串,但Python 3中已经移除了这个函数——因为Python 3的字符串默认就是Unicode编码,不需要专门的转换函数,直接调用会触发NameError。- 不存在名为
unicode的PyPI官方包,所以pip install unicode必然失败,出现ModuleNotFoundError。
2. 代码修复方案
方案一:直接适配Python 3(推荐)
把代码里的unicode()替换成Python 3的str()即可,两者在功能上等价:
def makelist(table): result = [] allrows = table.findAll('tr') for row in allrows: result.append([]) allcols = row.findAll('td') for col in allcols: thestrings = [str(s) for s in col.findAll(text=True)] thetext = ''.join(thestrings) result[-1].append(thetext) return result
方案二:兼容Python 2和Python 3
如果需要代码在两个版本都能运行,可以加入版本判断:
import sys # 根据Python版本映射unicode函数 if sys.version_info[0] == 2: unicode = unicode else: unicode = str def makelist(table): result = [] allrows = table.findAll('tr') for row in allrows: result.append([]) allcols = row.findAll('td') for col in allcols: thestrings = [unicode(s) for s in col.findAll(text=True)] thetext = ''.join(thestrings) result[-1].append(thetext) return result
内容的提问来源于stack exchange,提问作者Bruce Seymour
相关产品推荐
相关产品推荐

