Python LXML方法检查变量值是否有非ASCII值,如果有返回unicode值

2024-04-19 12:21:19 发布

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

我正在尝试使用LXML在python中创建xml。来自外部数据源的变量值用于在xml文件中输入值。如果变量的值包含非ASCII字符,如€,则会导致

ValueError: All strings must be XML compatible: Unicode or ASCII, no NULL bytes or control characters.

问:我想要一个python中的方法来检查变量中的值是否包含非ASCII值,如果是,则为该变量返回相应的unicode值,以便我可以对xml使用相同的值? 我不是在找输入\u string=u'string€。如我所说,变量从外部数据源获取其值。请帮忙


Tags: or文件stringasciixmlbeall字符
1条回答
网友
1楼 · 发布于 2024-04-19 12:21:19

你好像在找这个:
(假设Python2.7和<type 'str'>的输入数据)

# function that converts input_string from 'str' to 'unicode'
# only if input_string contains non-ASCII bytes 

def decode_if_no_ascii(input_string):

    try:
        input_string.decode('ascii')
    except UnicodeDecodeError:
        input_string = input_string.decode('utf-8') # 'utf-8' should match the encoding of input_string,
                                                    # it could be 'latin_1' or 'cp1252' in a particular case            
    return input_string

让我们测试一下函数:

# 1. ASCII str
input_string = 'string' 
input_string = decode_if_no_ascii(input_string)
print type(input_string), repr(input_string), input_string
# <type 'str'> 'string' string  
# ==> still 'str', no changes 

# 2. non-ASCII str
input_string = 'string €'
input_string = decode_if_no_ascii(input_string)
print type(input_string), repr(input_string), input_string
# <type 'unicode'> u'string \u20ac' string € 
# ==> converted to 'unicode'

这就是你要找的吗?你知道吗

相关问题 更多 >