gpt4 book ai didi

python - 如何从字符串中正确获取价格

转载 作者:太空宇宙 更新时间:2023-11-04 08:27:36 24 4
gpt4 key购买 nike

设置

我正在使用 Selenium 和 Python 3.x 网络抓取产品价格。

我有一个字符串列表,其中包含每个产品的价格。

对于低于 1000 欧元的价格,字符串看起来像 '€ 505.93 net'(即 505.93)。对于 1000 欧元起的价格,字符串看起来像 '€ 1 505.93 net'(即 1505.93)。


问题

我不确定如何巧妙地处理千价和点中的空间。

product_price = '€ 1 505.93 net',然后,

[int(s) for s in product_price if s.isdigit()]

给予,

[1, 5, 0, 5, 9, 3]

product_price = '€ 505.93 net' 的类似过程给出 [5, 0, 5, 9, 3]


问题

如何调整我的代码以得到 1505.93505.93

最佳答案

这是一种方法。我们可以匹配以下正则表达式模式,它使用空格作为千​​位分隔符:

€\s*(\d{1,3}(?: \d{3})*(?:\.\d+)?)

然后,第一个捕获组应包含匹配的欧元金额。

input = '€ 1 505.93 net and here is another price € 505.93'
result = re.findall(r'€\s*(\d{1,3}(?: \d{3})*\.\d+)', input)
print list(result)

['1 505.93', '505.93']

正则表达式的解释:

€                  a Euro sign
\s* followed by optional whitespace
( (capture what follows)
\d{1,3} one to three digits
(?: \d{3})* followed by zero or more thousands groups
(?:\.\d+)? an optional decimal component
) (close capture group)

关于python - 如何从字符串中正确获取价格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55690393/

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