2017-10-04 92 views
0

你好,我想打印在python3一个阿拉伯语的文本文件,这是我的代码:印刷阿拉伯文文本文件

#!/usr/bin/python3 
# -*- coding: utf-8 -*- 
# encoding: utf-8 
#Read from the input file 
input_file = open('triggertest.txt', 'r+') 
for line in input_file: 
    print (line) 

但我得到这个错误:

Traceback (most recent call last): 
    File "try.py", line 6, in <module> 
    for line in input_file: 
    File "/Users/emansaad/anaconda/lib/python3.5/encodings/ascii.py", line 26, in decode 
    return codecs.ascii_decode(input, self.errors)[0] 
UnicodeDecodeError: 'ascii' codec can't decode byte 0xd9 in position 0: ordinal not in range(128) 

时试试这个解决方案:

#!/usr/bin/python3 
# -*- coding: utf-8 -*- 
# encoding: utf-8 
#Read from the input file 
input_file = open('triggertest.txt', 'r+',encoding='utf-8') 
for line in input_file: 
    print (line) 

我得到这个错误:

Traceback (most recent call last): 
    File "try.py", line 7, in <module> 
    print (line) 
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-4: ordinal not in range(128) 

triggertest.txt:

مرحبا 
مرحباً بك 
السلام عليكم 
وعليكم السلام 
ماهو سعر الايفون٧؟ 
يأتي بسعتين ٣٢ قيقا ب ٢٤٩٩ ريال و ١٢٨ قيقا ٢٨٩٩ ريال 

运行locale时:

LANG= 
LC_COLLATE="C" 
LC_CTYPE="C" 
LC_MESSAGES="C" 
LC_MONETARY="C" 
LC_NUMERIC="C" 
LC_TIME="C" 
LC_ALL= 

当运行locale charmap

US-ASCII 
+2

[用波斯语/阿拉伯语字符的Python 3 print()函数(的可能的复制https://stackoverflow.com/questions/39528462/python -3-print-function-with-farsi-arabic-characters) – cosinepenguin

+0

@cosinepenguin我厌倦了解决方案,但没有运气 –

+0

'triggertest.txt'中的一行代码是什么? – cosinepenguin

回答

0

你可以这样做:

text = "مرحبا " 

print(text.encode('utf8')) 

检查本教程Arabic in python

+0

我得到了这个输出:b'\ xd9 \ x85 \ xd8 \ xb1 \ xd8 \ xad \ xd8 \ xa8 \ xd8 \ xa7',当我删除“。编码('utf8')“它回到错误 –

+0

我在这里看到另一个问题,它可能是我的语言环境和/或环境被打破,所以当我跑本地我得到这个:LANG = LC_COLLATE = “C” LC_CTYPE = “C” LC_MESSAGES = “C” LC_MONETARY = “C” LC_NUMERIC = “C” LC_TIME = “C” LC_ALL = –