2014-01-25 1 views
1

Я новичок в Python и мне нужна рука, чтобы работать этот код:строка convresion из входного файла

этот код работает правильно, он преобразует строки, как мне нужно.

# -*- coding: utf-8 -*- 
import sys 
import arabic_reshaper 
from bidi.algorithm import get_display 

reshaped_text = arabic_reshaper.reshape(u' الحركات') 
bidi_text = get_display(reshaped_text) 
print >>open('out', 'w'), reshaped_text.encode('utf-8') # This is ok 

Я получаю следующее сообщение об ошибке при попытке прочитать строку из файла:

# -*- coding: utf-8 -*- 
import sys 
import arabic_reshaper 
from bidi.algorithm import get_display 

with open ("/home/nemo/Downloads/mpcabd-python-arabic-reshaper-552f3f4/data.txt" , "r") as myfile: 
data=myfile.read().replace('\n', '')  
reshaped_text = arabic_reshaper.reshape(data) 
bidi_text = get_display(reshaped_text) 
print >>open('out', 'w'), reshaped_text.encode('utf-8') 

UnicodeDecodeError: «ASCII» кодек не может декодировать байт 0xd8 в положении 0: порядковый не в диапазоне (128).

Любая рука

Благодаря

ответ

2

The method decode() decodes the string using the codec registered for encoding. It defaults to the default string encoding.

При чтении UTF-8 кодируются файл, вам нужно использовать string.decode('utf8')

Запись:

data = 'my data' 
with open("file.txt" , "w") as f: 
    f.write(data.encode('utf-8')) 

Read:

with open("file.txt" , "r") as f: 
    data = f.read().decode('utf-8') 
2

Вы также можете использовать дополнительный encoding параметр встроенного open function:

with open("/home/nemo/Downloads/mpcabd-python-arabic-reshaper-552f3f4/data.txt", 
      'rt', 
      encoding='utf8') as f: