使用正则表达式很容易:
r'\s*\((\d+)\)'
这将匹配(可选)空格,后跟括号中的数字,并将数字放在一个组中以便于替换:
parensnumber = re.compile(r'\s*\((\d+)\)')
count = int(parensnumber.search(line).group(1))
for i in range(count):
print(parensnumber.sub('-{0}'.format(i + 1), line))
演示:
>>> import re
>>> parensnumber = re.compile(r'\s*\((\d+)\)')
>>> parensnumber.sub(r'-\1', 'itemA (3)')
'itemA-3'
>>> parensnumber.sub(r'-\1', 'itemB (test) abcd (2)')
'itemB (test) abcd-2'
>>> line = 'itemB (test) abcd (2)'
>>> count = int(parensnumber.search(line).group(1))
>>> for i in range(count):
... print(parensnumber.sub('-{0}'.format(i + 1), line))
...
itemB (test) abcd-1
itemB (test) abcd-2
您的特定示例的完整代码:
import os
import re
parensnumber = re.compile(r'\s*\((\d+)\)')
with open('C:\\Dropbox\\test.txt','r') as input:
for line in input:
count = int(parensnumber.search(line).group(1))
for i in range(count):
print(parensnumber.sub('-{0}'.format(i + 1), line))