在字符串中找到阿拉伯字串给出错误 'ascii' 编解码器无法解码

find arabic word string in string give error 'ascii' codec can't decode

我写这个函数是为了检查 uicode 字符串中是否存在波斯语的月份,替换 它与月数。 我在 header

中使用这个编码
`#!/usr/bin/python
# -*- coding: utf-8 -*-`

这是我转换月份的定义

def changeData(date):
                if date:
                   date.encode('utf-8')
                    if "فروردین".encode('utf-8') in date:
                        return str.replace(":فروردین", ":1")
                    elif "اردیبهشت".encode('utf-8') in date:
                        return str.replace(":اردیبهشت", ":2")
                    elif "خرداد".encode('utf-8') in date:
                        return str.replace(":خرداد", ":3")
                    elif "تیر".encode('utf-8') in date:
                        return str.replace(":تیر", ":41")
                    elif "مرداد".encode('utf-8') in date:
                        return str.replace(":مرداد", ":5")
                    elif "شهریور".encode('utf-8') in date:
                        return str.replace(":شهریور", ":6")
                    elif "مهر".encode('utf-8') in date:
                        return str.replace(":مهر", ":7")
                    elif "آبان".encode('utf-8') in date:
                        return str.replace(":آبان", ":8")
                    elif "آذر".encode('utf-8') in date:
                        return str.replace(":آذر", ":9")
                    elif "دی".encode('utf-8') in date:
                        return str.replace(":دی", ":10")
                    elif "بهمن".encode('utf-8') in date:
                        return str.replace(":بهمن", ":11")
                    elif "اسفند".encode('utf-8') in date:
                        return str.replace(":اسفند", ":12")

我在函数中使用 unicode 格式传递日期,然后将其转换为 encode('utf-8') 但给我这个错误

if "فروردین".encode('utf-8') in date:
UnicodeDecodeError: 'ascii' codec can't decode byte 0xd9 in position 0: ordinal not in range(128)

我该如何解决这个问题

我假设 Python 2.7.


所以:

"فروردین".encode('utf-8') # UnicodeDecodeError: 'ascii' codec can't decode byte 0xd9 in position 0: ordinal not in range(128)

问题在于 Python 2.7 字符串是字节:

print(repr("فروردین")) # '\xd9\x81\xd8\xb1\xd9\x88\xd8\xb1\xd8\xaf\xdb\x8c\xd9\x86'

使用以下代码:

"فروردین".encode('utf-8')

您正在尝试对逻辑上不正确的字节进行编码,因为:

ENCODING: unicode --> bytes 
DECODING: bytes --> unicode 

但是 Python 不会像 TypeError 那样乱扔东西,因为 Python 很聪明。
在这种情况下,它首先尝试将给定字节解码为 un​​icode,然后执行用户指定的编码。
问题是 Python 使用 Python 2 中的 ASCII 默认编码进行所描述的解码。因此程序以 UnicodeDecodeError 终止。

描述的解码类似于:

unicode("فروردین") # UnicodeDecodeError: 'ascii' codec can't decode byte 0xd9 in position 0: ordinal not in range(128)

所以,你不应该编码字节串,你必须解码它才能接收 unicode:

u = "فروردین".decode('utf-8') 
print(type(u)) # <type 'unicode'>

另一种获取unicode的方法是使用u-文字+编码声明:

# coding: utf-8

u = u"فروردین"
print(type(u)) # <type 'unicode'> 

print(u == "فروردین".decode('utf-8')) # True