【问题标题】:How to get exact number in set of numbers using regular expression in python?如何在python中使用正则表达式获取一组数字中的确切数字?
【发布时间】:2012-08-29 06:45:23
【问题描述】:

我已经在命令行中实现了程序,我编写了这样的代码:

import requests
import re
import sys

amount=[]
l=len(sys.argv)
from_=sys.argv[l-2]
to=sys.argv[l-1]
for i in range(1,l-2):
    amount.append(sys.argv[i])
for i in amount:
    r = requests.get("http://www.xe.com/ucc/convert/?Amount=%(amount)s&From=%(from_)s&To=%(to)s"%{"amount":i,"from_":from_,"to":to})
    #dataCrop=re.findall('[0-9,]+\.[0-9]+',r.text)
    dataCrop=re.compile(r'[0-9,]+\.[0-9]+')
    for m in dataCrop.finditer(r.text):
        print m.group()

当我运行程序时,我得到如下输出:

1.0
1.1
3.43
1.1
1.1
1.1
1999.09
1.1
1999.09
4.7
1.00
55.6565
55.6565
0.0179674
1.00000
0.79649
0.63231
55.6565
0.96365
0.98866
8.42406
1.24172
78.5433
1.00000
1.25551
1.58151
0.01797
1.03772
1.01147
0.11871
0.80533
0.01273
0.01797
0.01431
0.01136
1.00000
0.01731
0.01776
0.15136
0.02231
1.41122
55.6565
69.8771
88.0212
1.00000
57.7556
56.2947
6.60685
44.8219
0.70861
9.4
2.0

但我只想输出'55.6565'(在第12位和第11位)。我应该如何修改我的正则表达式?

【问题讨论】:

标签: python regex python-3.x python-2.7


【解决方案1】:

您必须购买他们的服务。当您这样做时,您将不得不处理不同格式的数据,但从编程的角度来看,总体思路是相同的。

首先,您需要匹配您获得的 HTML 中的正确行。然后在字符串中搜索在正确上下文中看起来像数字的内容,确保将实际数字捕获到一个组中。然后你就完成了。对于有问题的 HTML:

for line in r.text.split('\n'):  # This splits the entire HTML into lines.
  if re.search(r'<span class="uccResCde">INR</span>', line):
    match = re.search(r'>(?P<number>[0-9]+.[0-9]+)', line)
    if not match:
      raise Exception('Expected to find a number but did not.')
    print match.group('number')

这个输出:

55.5211

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-16
    • 1970-01-01
    • 2016-09-14
    • 2016-05-26
    相关资源
    最近更新 更多