【问题标题】:Convert a python list of strings into bytecode to write for writing into a file将 python 字符串列表转换为字节码以写入文件
【发布时间】:2019-01-28 02:23:58
【问题描述】:

我正在尝试训练 Keras 模型 (LipNet),在开始训练时,它会打开一个带有 wb 的文件,并尝试将标题写入列表中。但是,我收到此错误:

File "c:\users\fahim\documents\lipnet\lipnet\lipreading\callbacks.py", line 77, in on_train_begin
    csvw.writerow(['Epoch', 'Samples', 'Mean CER', 'Mean CER (Norm)', 'Mean WER', 'Mean WER (Norm)', 'Mean BLEU', 'Mean BLEU (Norm)'])
TypeError: a bytes-like object is required, not 'str'

我已经查看了这个问题并尝试了许多建议的方法,例如将 b 放在字符串前面,

csvw.writerow([b'Epoch', b'Samples', b'Mean CER', b'Mean CER (Norm)', b'Mean WER', b'Mean WER (Norm)', b'Mean BLEU', b'Mean BLEU (Norm)'])

并尝试将列表转换为字节码。

>>>bytes([1,2,3])
b'\x01\x02\x03'
>>>bytes(["a", "b"]) 
Traceback (most recent call last):
  File "<pyshell#7>", line 1, in <module>
    bytes(["a", "b"])
TypeError: 'str' object cannot be interpreted as an integer

这是打开文件的full code

(sn-p)

def on_train_begin(self, logs={}):
        with open(os.path.join(self.output_dir, 'stats.csv'), 'wb') as csvfile: #wb -> w
            csvw = csv.writer(csvfile)
            csvw.writerow([b'Epoch', b'Samples', b'Mean CER', b'Mean CER (Norm)', b'Mean WER', b'Mean WER (Norm)', b'Mean BLEU', b'Mean BLEU (Norm)'])

顺便说一句,如果有帮助,代码也会使用 pickle。 csvw如何将行写入字节码?

【问题讨论】:

    标签: python arrays file keras byte


    【解决方案1】:

    csv 总是想要文本文件,而不是二进制文件,但您可以尝试通过这样做来模拟:

    with open(os.path.join(self.output_dir, 'stats.csv'), 'w', encoding='utf-8', newline=''):
    

    【讨论】:

    • 谢谢,这解决了这里的问题,虽然还有一个TypeError: can't pickle _thread.lock objects
    • 这是一个不同的、不相关的错误。你试过用谷歌搜索吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-11-08
    • 1970-01-01
    • 1970-01-01
    • 2014-06-29
    • 1970-01-01
    • 1970-01-01
    • 2015-03-29
    相关资源
    最近更新 更多