Ich schreibe ein einfaches Python-Skript, um chinesische Interpunktion in Englisch zu übersetzen.Warum Python IDLE und Console unterschiedliche Ergebnisse produzieren
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)
Aber etwas ist mit UNICODE falsch. Ich kann es nicht bestehen. Fehler msg:
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
Nach dann teste ich die out.write() in IDLE und Konsole. Sie ergaben unterschiedliche Ergebnisse. Ich weiß nicht warum.
In 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
>>>
In Console
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
>>>
Plattform: Windows XP EN
Vielen Dank! Das hat mich für 2 Tage verrückt gemacht. Ich habe versucht "out = codecs.getwriter ('utf-8') (sys.stdout)" Es würde auf Linux funktionieren, aber nicht in Windows (nicht einmal in cygwin) – aiGuru