簡體   English   中英

在python中使用正則表達式在5位數字之前插入換行符

[英]Insert newline before 5 digits using regex in python

我有以下問題:我有一個 .txt 文件,其中包含以下方案中的信息:

ddddd name country time dddd name country time

ddddd 代表 5 位數字,代表與會者的 ID 號。 根據可用信息,我到目前為止:

filename = 'raw_race.txt'
new_filename = 'data_race.txt'

pattern = re.compile(r'\D(\d{5})\D')

with open(filename, 'r') as readfile, open(new_filename, 'w+') as writefile:
    for line in readfile:
        writefile.write(line)
        if pattern.search(line):
            writefile.write('\n')

這不起作用(輸出文件與輸入相同),而且,這會在模式之后而不是之前添加段落。

有沒有人看到我能做什么? 干杯!

for line in readfile:
    writefile.write(re.sub(r'\b(\d{5})\b', '\n\\1', line))

成功了,謝謝!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM