我编写了一个简单的Python脚本,用于将中文标点翻译为英文。
之后,我在IDLE和控制台中测试了
平台:Windows XP EN
import codecs, sys
def trcn():
tr = lambda x: x.translate(str.maketrans(""",。!?;:、()【】『』「」﹁﹂“”‘’《》~¥…—×""", """,.!?;:,()[][][][]""''<>~$^-*"""))
out = codecs.getwriter('utf-8')(sys.stdout)
for line in sys.stdin:
out.write(tr(line))
if __name__ == '__main__':
if not len(sys.argv) == 1:
print("usage:\n\t{0} STDIN STDOUT".format(sys.argv[0]))
sys.exit(-1)
trcn()
sys.exit(0)
但是 UNICODE 出了些问题。 我无法通过。错误信息:
Traceback (most recent call last):
File "trcn.py", line 13, in <module>
trcn()
File "trcn.py", line 7, in trcn
out.write(tr(line))
File "C:\Python31\Lib\codecs.py", line 356, in write
self.stream.write(data)
TypeError: must be str, not bytes
之后,我在IDLE和控制台中测试了
out.write()
函数,结果不同。我不知道为什么。
IDLE环境下:
Python 3.1.2 (r312:79149, Mar 21 2010, 00:41:52) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> import sys,codecs
>>> out = codecs.getwriter('utf-8')(sys.stdout)
>>> out.write('hello')
hello
>>>
在控制台中
Python 3.1.2 (r312:79149, Mar 21 2010, 00:41:52) [MSC v.1500 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys,codecs
>>> out = codecs.getwriter('utf-8')(sys.stdout)
>>> out.write('hello')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python31\Lib\codecs.py", line 356, in write
self.stream.write(data)
TypeError: must be str, not bytes
>>>
平台:Windows XP EN