【问题标题】:Reading a Txt File into Python 3.5 with Korean and English characters in it将包含韩文和英文字符的 Txt 文件读入 Python 3.5
【发布时间】:2016-04-27 16:05:46
【问题描述】:

我正在尝试读取包含韩文和英文的 txt 文件。
这是一个示例:
52:15 问候。 안녕하십니까.

我的代码是:

# Read a line and Split into tokens                                                                  
f = open(infile, 'r')
for line in f:
    if( matchObj = re.match( r"(\d\d:\d\d)\t([^\t]+)\t(.*)$", line )
        startTC, englishSubtitle, foreignSubtitle = matchObj.group(1), matchObj.group(2), matchObj.group(3)
    else:
        SyntaxError(line)

当我在运行 El Capitan 的 2012 Macbook Pro 上将它读入 python (3.5) 时,我收到错误消息(在底部)。

错误信息:

python3 *.py
Traceback (most recent call last):
File "txtToSrt.py", line 48, in <module>
readFileData( "Korean.txt" )
File "txtToSrt.py", line 26, in readFileData
for line in f:
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/codecs.py", line 321, in decode
(result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xfe in position 0: invalid start byte

您能否建议如何阅读此内容。

【问题讨论】:

  • 0xfe - 可以是BOM

标签: python text fonts character-encoding non-ascii-characters


【解决方案1】:

我在顶部添加了以下行:

import codecs

并改行读取文件如下:

f = open(infile, 'r', encoding="utf-16")

现在可以读取数据,但不能写入文件。要写的代码是:

outfile = open("out.txt", 'w')
outfile.write( "{0}\n{1}\n".format(startTC, foreignSubtitle.encode("utf-16")) )

我得到的输出是:

01:00:01:16
b'\xff\xfe\x14\xbc\x98\xb0\x90\xc7'

我希望输出的第二行以韩语显示。我怎样才能做到这一点? 谢谢。

【讨论】:

    【解决方案2】:

    不幸的是,Python 的韩元符号似乎有问题。 尝试以下方法来确认 python 3.5:

    a_string = 'à'.encode ('utf-8')
    print (a_string)
    
    b_string = '₩'.encode ('utf-8')
    print (b_string)
    
    a_bytes = a_string.decode ('utf-8')
    print (a_bytes)
    
    b_bytes = b_string.decode ('utf-8')
    print (b_bytes)
    

    【讨论】:

    • 谢谢你,雅克。
    猜你喜欢
    • 1970-01-01
    • 2018-07-18
    • 1970-01-01
    • 1970-01-01
    • 2012-06-26
    • 1970-01-01
    • 1970-01-01
    • 2012-01-07
    • 1970-01-01
    相关资源
    最近更新 更多