gpt4 book ai didi

python - 在 Python 2.7 中将 ½ 解析为 0.5

转载 作者:太空狗 更新时间:2023-10-30 00:31:36 25 4
gpt4 key购买 nike

我正在抓取 this link使用 BeautifulSoup4

我正在像这样解析页面 HTML

page = BeautifulSoup(page.replace('ISO-8859-1', 'utf-8'),"html5lib")

你可以看到像这样的值-4 -115(用-分隔)

我想要一个列表中的两个值,所以我使用这个正则表达式。

value = re.findall(r'[+-]?\d+', value)

它工作得很好,但不适用于这些值 +2½ -102,我只得到 [-102]

为了解决这个问题,我也尝试过

value = value.replace("½","0.5")
value = re.findall(r'[+-]?\d+', value)

但这给了我关于编码的错误,说我必须设置我的文件的编码。

我也试过在文件顶部设置 encoding=utf-8 但仍然给出同样的错误。

我想问一下如何将½转换为0.5

最佳答案

要在 Python 2 脚本中嵌入 ½ 等 Unicode 文字,您需要在脚本顶部使用特殊注释,让解释器知道 Unicode 是如何编码的。如果你想使用 UTF-8,你还需要告诉你的编辑器将文件保存为 UTF-8。如果您想打印 Unicode 文本,请确保您的终端也设置为使用 UTF-8。

这是一个简短的例子,在 Python 2.6.6 上测试

# -*- coding: utf-8 -*-

value = "a string with fractions like 2½ in it"
value = value.replace("½",".5")
print(value)

输出

a string with fractions like 2.5 in it

请注意,我使用 ".5" 作为替换字符串;使用 "0.5" 会将 "2½" 转换为 "20.5",这是不正确的。


实际上,这些字符串应该被标记为 Unicode 字符串,像这样:

# -*- coding: utf-8 -*-

value = u"a string with fractions like 2½ in it"
value = value.replace(u"½", u".5")
print(value)

有关在 Python 中使用 Unicode 的更多信息,请参阅 Pragmatic Unicode ,由 SO 资深人士 Ned Batchelder 撰写。


我还应该提到,您需要更改您的正则表达式模式,以便它允许在数字中使用小数点。例如:

# -*- coding: utf-8 -*-
from __future__ import print_function
import re

pat = re.compile(r'[-+]?(?:\d*?[.])?\d+', re.U)

data = u"+2½ -105 -2½ -115 +2½ -105 -2½ -115 +2½ -102 -2½ -114"
print(data)
print(pat.findall(data.replace(u"½", u".5")))

输出

+2½ -105 -2½ -115 +2½ -105 -2½ -115 +2½ -102 -2½ -114
[u'+2.5', u'-105', u'-2.5', u'-115', u'+2.5', u'-105', u'-2.5', u'-115', u'+2.5', u'-102', u'-2.5', u'-114']

关于python - 在 Python 2.7 中将 ½ 解析为 0.5,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35012491/

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