如何格式化这个python正则表达式?

2024-09-29 03:34:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图解析文本文件中的数据。数据元组是一个年龄,后面的0-3次都是“右”对齐的。无论在源数据中跟随一个年龄多少次,我都要None“pad”三次。年龄和时间都是用空格隔开的,而且时间的格式是“mm:不锈钢dd“或”不锈钢dd". 年龄和时间可以在一行中重复一次或多次。你知道吗

以下是一些示例数据:

test_str = ['25',
    '24 22.10',
    '16 59.35 1:02.44',
    '18 52.78 59.45 1:01.22',
    '33 59.35 1:02.44 34 52.78 59.45 1:01.22 24 25']

扫描,上面应该产生元组(或列表,dicts。。。不管怎样)

(25, None, None, None)
(24, None, None, 0:22.10)
(16, None, 0:59.35, 1:02.44)
(18, 0:52.78, 0:59.45, 1:01.22)
(33, None, 0:59.35, 1:02.44), (34, 0:52.78, 0:59.45, 1:01.22), (24, None, None, None), (25, None, None)

我的想法是使用正则表达式,大致如下:

data_search = r'[1-9][0-9]( (([1-9][0-9]:)?[0-9]{2}.[0-9]{2})|){3}'
x = re.search(data_search, test_str[0])

但我没有成功。你知道吗

有人能帮我用正则表达式吗,或者建议一个更好的解决方案?


Tags: 数据testnonesearchdata时间dd元组
3条回答
>>> age_expr = r"(\d+)"
>>> time_expr = r"((?:\s+)(?:\d+:)?\d+\.\d+)?"
>>> expr = re.compile(age_expr + time_expr * 3)
>>> [expr.findall(s) for s in test_str]
[[('25', '', '', '')], [('24', ' 22.10', '', '')], [('16', ' 59.35', ' 1:02.44', '')], [('18', ' 52.78', ' 59.45', ' 1:01.22')], [('33', ' 59.35', ' 1:02.44', ''), ('34', ' 52.78', ' 59.45', ' 1:01.22'), ('24', '', '', ''), ('25', '', '', '')]]

我不确定这是否是最好的方法,但这会分割第一个元素,因为它总是静态地位于第一个位置,然后分割其余元素并用None填充间隙。你知道吗

test_str = ['25',
            '24 22.10',
            '16 59.35 1:02.44',
            '18 52.78 59.45 1:01.22']

def create_tuples(string_list):
    all_tuples = []
    for space_string in string_list:
        if not space_string:
            continue
        split_list = space_string.split()
        first_list_element = split_list[0]
        last_list_elements = split_list[1:]
        all_tuples.append([first_list_element] + [None] * (3 - len(last_list_elements)) + last_list_elements)
    return all_tuples

print(create_tuples(test_str))

# Returns:
[['25', None, None, None], ['24', None, None, '22.10'], ['16', None, '59.35', '1:02.44'], ['18', '52.78', '59.45', '1:01.22']]

我相信这已经接近你想要的了。抱歉没有正则表达式。你知道吗

def format_str(test_str):
    res = []
    for x in test_str:
        parts = x.split(" ")
        thing = []
        for part in parts:
            if len(thing) != 0 and '.' not in part and ':' not in part:
                res.append(thing[:1] + [None]*(4-len(thing)) + thing[1:])
                thing = [part]
            else:
                thing.append(part)
        if len(thing) != 0:
            res.append(thing[:1] + [None]*(4-len(thing)) + thing[1:])
    return res

test_str = ['25',
    '24 22.10',
    '16 59.35 1:02.44',
    '18 52.78 59.45 1:01.22 24 22.10']

results = format_str(test_str)
print(results)

结果是:

[['25', None, None, None], ['24', None, None, '22.10'], ['16', None, '59.35', '1:02.44'], ['18', '52.78', '59.45', '1:01.22'], ['24', None, None, '22.10']]

我没有在时报上做任何格式化,所以52.78没有显示为0:52.78,但我打赌你可以做到。如果没有,请留下评论,我也会为此编辑一个解决方案

相关问题 更多 >