中国語の句読点を英語に翻訳するための簡単なPythonスクリプトを書いています。なぜpython IDLEとコンソールは異なる結果を生成する
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
ありがとうございました!これは2日間ナッツを運転しています。私は "out = codecs.getwriter( 'utf-8')(sys.stdout)を試していました。Linuxでは動作しますがWindowsでは動作しません(cygwinではなく) – aiGuru