Python: テキスト中の数字を全てインクリメントする
目的
Vim における Ctrl-A (Increasing or decreasing numbers - Vim Tips Wiki) のように
テキスト中の数字を全てインクリメントする処理を Python で行いたい。
コード
textprocessor を利用する。
正規表現モジュールの split 関数を利用して1行分の文字列を「数字部分」と「数字以外」に切り分けて、
数字部分のみを +1 することでシンプルに書けた。
今回は「0」で始まる2文字以上の数字(00, 01 など)は特別にインクリメント対象から除外している。
また、マイナス記号は単なる「数字以外の文字」として扱われるため、負数のインクリメントには対応していない。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | #!/usr/bin/env python # -*- coding: utf-8 -*- import re import textprocessor tokenizer = re. compile (r '(\d+)' ).split def convert(token): if token ! = '0' and token.startswith( '0' ): return token return str ( int (token) + 1 ) def increment(line): tokens = tokenizer(line) tokens = [x if i % 2 = = 0 else convert(x) for (i, x) in enumerate (tokens)] print (''.join(tokens)) if __name__ = = '__main__' : textprocessor.process(increment) |
実行例
- 準備したファイル
test.txt 123456789101112a
1
b2
3c
d4e
5f6
7 8 9
w0rd
-5 -4 -3 -2 -1 0 1 2 3 4 5
[0, 00, 01, 02, 03, 04, 05]
0.0 1.1 2.2 3.3 4.4 5.5
9.99 999.9999 99999.999999
- 実行結果
12345678910111213$ ./increment.py ./test.txt
a
2
b3
4c
d5e
6f7
8 9 10
w1rd
-6 -5 -4 -3 -2 1 2 3 4 5 6
[1, 00, 01, 02, 03, 04, 05]
1.1 2.2 3.3 4.4 5.5 6.6
10.100 1000.10000 100000.1000000
GitHub
0 件のコメント:
コメントを投稿