输入fi的字符串转换

2024-05-18 18:22:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要编写一些新代码:

这段代码工作正常,它可以根据需要转换字符串。在

# -*- 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

尝试从文件中读取字符串时出现以下错误:

^{pr2}$

UnicodeDecodeError:“ascii”编解码器无法解码位置0中的字节0xd8:序号不在范围(128)。在

任何一只手

谢谢


Tags: 字符串代码textfromimportgetdisplaysys
2条回答

您还可以使用内置的open function的可选encoding参数:

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

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'))

阅读:

^{pr2}$

相关问题 更多 >

    热门问题