寻找一种将价格解析为十进制的通用方法

时间:2016-12-07 17:04:43

标签: python python-2.7 parsing

我正在开展一个我需要解析价格的项目。我必须考虑不同的价格格式。

问题:

美国公民以这种方式写价格:1,000.00

欧盟这样:1.000,00

这个问题可以用逗号和点分解字符串来解决,所以列表中的最后一项是美分。问题在于,有时人们根本不写分数,所以有人可以写1.000欧元。

还有其他问题......有时人们根本不写点。

你知道一些python模块或函数可以解决这个问题并返回<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="gallery-category"> <h2 data-gallery="Exterior"> <span class="gallery-back"></span> Exterior </h2> <div class="gallery-items-wrap"> <div class="gallery-image-tile"> <div class="gallery-img" data-analytics="photo-click"> <picture> <source srcset="/content/image/image1.jpg"> </picture> </div> </div> </div> </div> <div class="gallery-category"> <h2 data-gallery="Interior"> <span class="gallery-back"></span> Interior </h2> <div class="gallery-items-wrap"> <div class="gallery-image-tile"> <div class="gallery-img" data-analytics="photo-click"> <picture> <source srcset="/content/image/image2.jpg"> </picture> </div> </div> </div> </div>的价格吗?我不关心货币。

编辑:假设我将以这种格式获得数千个价格。

2 个答案:

答案 0 :(得分:2)

此代码使用以下逻辑:

  • 如果没有'。'或','存在,只转换为浮动
  • 否则,如果','或'。'是结尾的第3个字符,那么这是十进制字符:

    。 strip然后是非十进制字符,将十进制char更改为'。'如有必要,然后转换为浮动

  • 否则

    。没有给出小数部分,只需删除所有','和'。'并转换为浮动

此代码非常依赖于获取有效字符串 - "1..."def parse_price(s): if '.' not in s and ',' not in s: return float(s) elif s[-3] in ',.': dec_char = s[-3] sep_char = {'.': ',', ',':'.'}[dec_char] s = s.replace(sep_char, '') s = s.replace(',', '.') return float(s) else: s = s.replace(',','').replace('.', '') return float(s) tests = """\ 1.000 1.000,20 23.14 1,234 1.23 3,12 """.splitlines() for test in tests: print(test, '->', parse_price(test)) 等无效字符串会产生错误的值。

1.000 -> 1000.0
1.000,20 -> 1000.2
23.14 -> 23.14
1,234 -> 1234.0
1.23 -> 1.23
3,12 -> 3.12

给出

<div style="width: 100%; overflow: hidden;">
<div style="width: 10%; float: left;"> <div><img src="assets/img/abc.png" style="height: 35;margin-left: 10; margin-right: 5px;"/></div> <div id="toro" style="color: black">  Hi </div></div>
<div style="margin-left: 25%;"><div style="margin-top: 7;
font-weight: bold; color: black">  <b>hie</b></div> <div style="color: black" >  Hello  </div><div style="float: right" id="time">time</div></div>

答案 1 :(得分:0)

使用price-parser

>>> from price_parser import parse_price
>>> parse_price('1,000.00')
Price(amount=Decimal('1000.00'), currency=None)
>>> parse_price('1.000,00')
Price(amount=Decimal('1000.00'), currency=None)
相关问题