【问题标题】:must be unicode not string on python 2必须是 unicode 而不是 python 2 上的字符串
【发布时间】:2019-01-09 17:49:34
【问题描述】:

我试图在 Python 2 上运行 python 3 代码,但它给了我这个错误:

TypeError: 必须是 unicode,而不是 str 我试过在 chr(i) 之前添加 str() 和在 "P" 之前添加 "u" 但我显然做错了。

tbl = dict.fromkeys(i for i in range(sys.maxunicode)
                    if unicodedata.category(chr(i)).startswith("P"))
def remove_punctuation(text):
        return text.translate(tbl)

    # initialize the stemmer
    stemmer = LancasterStemmer()
    # variable to hold the Json data read from the file
    data = None

    # read the json file and load the training data
    with open('data.json') as json_data:
        data = json.load(json_data)
        print(data)

【问题讨论】:

  • 在 Python 3 上运行它怎么样?
  • 不能,因为 Tensorflow、Keras 和其他一切都可以在这台 PC 上的 Python 2 下正常工作。
  • 你必须决定:Python 3 还是 Python 没有 Python 3 代码。顺便说一句,Tensorflow 和 Keras 在 Python 3.6 上运行良好。

标签: python unicode


【解决方案1】:

在 Python 2 上使用 unichr 而不是 chr 从序数创建 Unicode 字符:

tbl = dict.fromkeys(i for i in range(sys.maxunicode)
                    if unicodedata.category(unichr(i)).startswith("P"))

如果可以的话,切换到 Python 3。 Python 2 支持将于明年结束。

【讨论】:

  • 谢谢!会做。我现在需要快速修复,到时我将在下一台 PC 上使用 Python 3。
猜你喜欢
  • 1970-01-01
  • 2017-04-12
  • 2017-01-28
  • 1970-01-01
  • 1970-01-01
  • 2016-02-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多