Skip to main content
 首页 » 编程设计

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

2025年05月04日34zhoujg

设置

我正在使用 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.93 和 505.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)