2016-01-21 62 views
0

我想读在它韩文和英文TXT文件。
下面是一个例如:
52:15问候。 안녕하십니까。阅读TXT文件成Python 3.5,韩文和英文字符在它

我的代码是:

# 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) 

当我在2012年的MacBook Pro运行埃尔卡皮坦读入蟒(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 

可否请你建议如何在阅读本

+0

'0xfe' - 它可以是[BOM(https://en.wikipedia.org/wiki/Byte_order_mark) – furas

回答

1

似乎不幸的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) 
+0

谢谢你,雅克。 – Rajnesh

0

我加在顶部以下行:

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' 

我想输出出现在韩国的第二行。我怎样才能做到这一点? 谢谢。