【问题标题】:Python regex with parenthesis and decimal place带括号和小数位的 Python 正则表达式
【发布时间】:2016-08-03 15:38:22
【问题描述】:

我正在查看Python 2.7 中的复杂正则表达式,以从文件中读取以下格式。这些行(读取为字符串)如下所示:

 line = 23.3(14) 600(3)   760.35(10)

最终所需的输出将是一个列表(或其他),它将行解析为:

list = 23.3 1.4 600 3 760.35 0.10 ; list[0]=23.3, list[1]=1.4 ....

正则表达式应该读取() 之间的数字,但也计算它前面的数字(紧靠左边)的位数,以正确解释() 之间的值。

示例:23.3 小数点后有 1 位,所以在下一个 () 之间有 14 将读取 1.4 = 14/10。如果 23.30 则 0.14=14/100。

如果可能,请告诉我。多谢你们。

【问题讨论】:

  • 正则表达式不能数数也不能除数,它们匹配文本。您可以使用正则表达式来匹配您的数字,然后编写一个 Python 函数来确定小数点后的位数。
  • @Tim:感谢您的反馈。您对正则表达式或函数部分有什么建议吗?

标签: regex python-2.7 format decimal parentheses


【解决方案1】:

这样的事情怎么样:

import re
s = "23.3(14) 600(3)   760.35(10)"

def digits(s):                # return the number of digits after the decimal point
    pos = s.find(".")
    if pos == -1:             # no decimal point
        return 0
    else:
        return len(s)-pos-1   # remember that indices are counted from 0

matches = re.findall(r"([\d.]+)\((\d+)\)", s) # find all number pairs
l = []
for match in matches:
    d = digits(match[0])
    if d:                     # More than 0 digits?
        l.append((float(match[0]), float(match[1]) / 10**d))
    else:                     # or just integers?
        l.append((int(match[0]), int(match[1])))

生成的l[(23.3, 1.4), (600, 3), (760.35, 0.1)]

【讨论】:

  • @Tim:工作也很完美。我只是对列表格式有一点偏好,以便进一步处理。
【解决方案2】:

你也可以去:

import re

line = "23.3(14) 600(3)   760.35(10)"

# split the items
rx = re.compile(r"\d[\d().]+")
digits = rx.findall(line)

# determine the length
def countandsplit(x):
    ''' Finds the length and returns new values'''
    a = x.find('(')
    b = x.find('.')
    if a != -1 and b != -1:
        length = a-b-1
    else:
        length = 0

    parts = list(filter(None, re.split(r'[()]', x)))
    number1 = float(parts[0])
    number2 = round(float(parts[1]) * 10 ** -length, length)
    return [number1, number2]

# loop over the digits
result = [x for d in digits for x in countandsplit(d)]
print(result)
# [23.3, 1.4, 600.0, 3.0, 760.35, 0.1]


a demo on ideone.com

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-23
    相关资源
    最近更新 更多