【问题标题】:How to load string in unicode using Textract library in Python?如何使用 Python 中的 Textract 库在 unicode 中加载字符串?
【发布时间】:2016-09-23 16:53:05
【问题描述】:

我正在使用Textract 并且对 Python 来说相对较新,我想以 unicode 字符串而不是 utf-8 加载文件。有没有办法做到这一点?

我试过了

text = textract.process(file)

但这会加载一个 UTF-8 字符串,而我更喜欢 unicode。我尝试使用

text = textract.process(file, encoding="unicode")

但这会引发错误。

Error
Traceback (most recent call last):
  File "/home/moha/dev/intellij-ws/pyqadi/tests/test_file2txt.py", line 11, in test_process
    str=f2t.to_txt(file)
  File "/home/moha/dev/intellij-ws/pyqadi/textsearcher/file2txt.py", line 10, in to_txt
    text = textract.process(file, encoding="unicode")
  File "/usr/local/lib/python2.7/dist-packages/textract/parsers/__init__.py", line 57, in process
    return parser.process(filename, encoding, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/textract/parsers/utils.py", line 46, in process
    return self.encode(unicode_string, encoding)
  File "/usr/local/lib/python2.7/dist-packages/textract/parsers/utils.py", line 31, in encode
    return text.encode(encoding, 'ignore')
LookupError: unknown encoding: unicode

【问题讨论】:

  • Utf-8 是 unicode 字符串的编码。我不明白你在问什么。你能解释一下吗?你能添加print type(text)的输出吗?

标签: python python-2.7 unicode


【解决方案1】:

Textract 使用 encoding 来指定特定的输出编码(输入编码使用chardet 推断

这里是用于编码的 Uncidoe 选项:

unicode_escape, unicode_internal, raw_unicode_escape
text = textract.process(file, encoding = 'unicode_escape')

这是exhaustive list

基础数据采用 UTF-8 格式。您可以将 textract.processn 作为 UTF-8 并在单独的行上将其解码为 Unicode:

text = textract.process(file)

Utext = unicode(text,'utf-8')

【讨论】:

    【解决方案2】:

    这个简单的方法对我有用:

    import textract as txt
    text = txt.process(file)
    text = text.decode("utf8")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-30
      • 1970-01-01
      • 2017-09-26
      • 1970-01-01
      • 1970-01-01
      • 2016-11-28
      • 1970-01-01
      • 2014-09-16
      相关资源
      最近更新 更多