【问题标题】:TypeError: character mapping must return integer, None or unicodeTypeError:字符映射必须返回整数、无或 unicode
【发布时间】:2017-06-21 14:21:18
【问题描述】:

我无法弄清楚这个错误是什么以及如何修复它。

    texts = [[word for word in document.translate(trans_table).lower().split()] for document in live_text]

TypeError: character mapping must return integer, None or unicode

我的代码:

rows=cursor.fetchall()
listTSeps=[]

for row in rows:
    listTSeps.append(re.sub('[^A-Za-z0-9]+', ' ', row[0]))

#Close cursor and connection done reading from database
cursor.close()
conn.close()


live_text=listTSeps
trans_table = ''.join( [chr(i) for i in range(128)] + [' '] * 128 )

texts = [[word for word in document.translate(trans_table).lower().split()] for document in live_text]

text_matrix = ["None"]*len(live_text)

我通过网络搜索得出的结论是,这可以使用 .encode('ascii') 或 ord() 来解决。

我是 python 的业余爱好者,并试图从示例代码中学习。我是从一个朋友那里看到的。有人可以解释一下问题的根源以及如何解决它。谢谢。

【问题讨论】:

  • 在哪一行抛出错误?
  • 这里:texts = [[word for word in document.translate(trans_table).lower().split()] for document in live_text]
  • 你的 Python 版本是多少? Python 3.0 到 3.3 不允许转换表使用字符串,但需要映射。
  • 在 Anaconda 中使用 Python 2.7

标签: python unicode typeerror python-unicode


【解决方案1】:

您的documentunicode,而不是str。对于unicodetranslate() 方法需要有所不同,而不是 256 个字符的字符串。

help(u' '.translate)

产量:

Help on built-in function translate:

translate(...)
    S.translate(table) -> unicode

    Return a copy of the string S, where all characters have been mapped
    through the given translation table, which must be a mapping of
    Unicode ordinals to Unicode ordinals, Unicode strings or None.
    Unmapped characters are left untouched. Characters mapped to None
    are deleted.

这样的字典很好:

u'abcd efgh'.translate({ 32: u'x' })
u'abcdxefgh'

对于您只想用空格替换 ASCII 127 以上的所有字符的情况,您可能需要考虑:

re.sub(r'[^\x00-\x7f]', ' ', u'abcdäefgh')
u'abcd efgh'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-27
    • 2012-05-09
    • 2022-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-05
    相关资源
    最近更新 更多