gpt4 book ai didi

Python - 'ascii' 编解码器无法在位置解码字节\xbd

转载 作者:太空狗 更新时间:2023-10-30 02:11:48 25 4
gpt4 key购买 nike

我正在使用 LXML 从网页上抓取一些文本。一些文本包括分数。


我需要将其转换为浮点格式。这些失败了:

ugly_fraction.encode('utf-8')  #doesn't change to usable format
ugly_fraction.replace('\xbd', '') #throws error
ugly_freaction.encode('utf-8').replace('\xbd', '') #throws error

最佳答案

unicodedata.numeric :

Returns the numeric value assigned to the Unicode character unichr as float. If no such value is defined, default is returned, or, if not given, ValueError is raised.

请注意,它只处理单个字符,而不处理字符串。因此,您仍然需要编写将由整数和小数字符组成的“带分数”转换为 float 的代码。但这很容易。例如。您只需要想出关于如何在数据中表示带分数的规则。例如,如果纯整数、纯分数和整数后跟一个中间没有空格的分数是唯一的可能性,这可行(包括为所有无效情况引发某种合理的异常):

def parse_mixed_fraction(s):
if s.isdigit():
return float(s)
elif len(s) == 1:
return unicodedata.numeric(s[-1])
else:
return float(s[:-1]) + unicodedata.numeric(s[-1])

关于Python - 'ascii' 编解码器无法在位置解码字节\xbd,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20110578/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com