【问题标题】:What is the encoding getting used in tf.gfile.GFile()?tf.gfile.GFile() 中使用的编码是什么?
【发布时间】:2018-02-22 21:38:46
【问题描述】:

tf.gfile.GFile() 不接受“编码”参数。从here 我收集到 gfile 只返回一个字节流,但现在似乎已经改变为:

with tf.gfile.GFile("./data/squad/test1.txt", mode = "rb") as file1:
    print(file1.read(n = 2), type(file1.read(n = 2)))
with tf.gfile.GFile("./data/squad/test1.txt", mode = "r") as file1:
    print(file1.read(n = 2), type(file1.read(n = 2)))

输出:

b'as' <class 'bytes'>
as <class 'str'>

那么它在读取这些字符串时使用的编码到底是什么?是 utf8 还是依赖于平台,就像 python 中的开放协议一样?

【问题讨论】:

  • 我的理解是它在模仿python的行为。

标签: python python-3.x tensorflow encoding


【解决方案1】:

据我了解的实现,tf.io.gfile.GFile 始终使用 UTF-8:https://github.com/tensorflow/tensorflow/blob/b3376f73ccfd6ae8721a946daf064675ee19b427/tensorflow/python/lib/io/file_io.py#L100

def write(self, file_content):
  """Writes file_content to the file. Appends to the end of the file."""
  self._prewrite_check()
  self._writable_file.append(compat.as_bytes(file_content))

它使用编码为 UTF-8 的tf.compat.as_bytesstr 转换为bytes

【讨论】:

    【解决方案2】:

    只是一个byte-stream,所以由你决定你的文本的字节编码是什么。

    您可以使用库来检测编码并将其用作解码方法。截至今天(2020 年 6 月),用于编码检测的最佳 Python 库之一是 chardet,来自 Mozilla 的优秀人员

    pip install chardet
    

    如果您知道是 'utf-8',您可以使用

    对其进行解码
    import chardet
    
    bstream = file1.read()
    info = chardet.detect(bstream)
    enc = info['encoding']
    info['confidence']
    text = bstream.decode(enc)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-05
      • 1970-01-01
      • 1970-01-01
      • 2011-07-21
      • 2014-10-24
      相关资源
      最近更新 更多