作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我正在使用 LXML 从网页上抓取一些文本。一些文本包括分数。
5½
我需要将其转换为浮点格式。这些失败了:
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
最佳答案
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/
我是一名优秀的程序员,十分优秀!