我试图在特定字符之后和特定字符之前找到一个整数,然后为其添加一个整数。
我有这个。
import re filedata = None with open('doc.txt', 'r') as file : filedata = file.read() count = int(filedata.count('~')) # 454 m = re.search('~RR\*(\d+)\*', filedata); print(m) with open('docresult.txt', 'w') as file: file.write(filedata)</pre>所以我必须完成的任务是在~RR\* XXX *之间加上数字,并将其替换。
所以,如果在一开始我有~RR*120*和我的计数是50我希望新文件说~RR*170*
我也尝试过使用re.compile但没有结果。
I'm trying to find an integer after certain characters and before certain characters, and add an integer to that.
I have this.
import re filedata = None with open('doc.txt', 'r') as file : filedata = file.read() count = int(filedata.count('~')) # 454 m = re.search('~RR\*(\d+)\*', filedata); print(m) with open('docresult.txt', 'w') as file: file.write(filedata)</pre>So what I have to accomplish is add count to whatever digits are between ~RR\* XXX * and replace it.
So if at the beginning I had ~RR*120* and my count is 50 I want the new file to say ~RR*170*
I tried also with re.compile but had no results.
最满意答案
不确定你的计算(例如,120 + 50如何能够产生175),但是当它们与你的奇怪的~RR*<a number>* pattern使用re.sub 替换函数相匹配时,对你的整数进行计算的替换字符串。
替换函数在与匹配对象匹配时作为唯一参数调用。 它必须返回替换字符串。
import re global count count = 50 filedata = "hello ~RR*120* foo ~RR*40*" def repl_function(m): return str(int(m.group(1))+count+len(m.group(1))) filedata = re.sub('(?<=~RR\*)(\d+)(?=\*)', repl_function, filedata) print(filedata)该独立示例打印:
hello ~RR*173* foo ~RR*92*我们看到这些数字已经被提取,计算并以原始字符串替换。 我使用了非消费(lookbehind / lookahead)组,因此只有数字被传递给替换字符串,并且包装模式保存在更新后的字符串中。
Not sure about your computations (how 120+50 can yield 175 for instance), but here's a way to perform computations on your integers when they match your strange ~RR*<a number>* pattern using re.sub with a replacement function instead of a replacement string.
The replacement function is called on a match with the match object as sole parameter. It must return the replacement string.
import re global count count = 50 filedata = "hello ~RR*120* foo ~RR*40*" def repl_function(m): return str(int(m.group(1))+count+len(m.group(1))) filedata = re.sub('(?<=~RR\*)(\d+)(?=\*)', repl_function, filedata) print(filedata)that stand-alone example prints:
hello ~RR*173* foo ~RR*92*We see that the numbers have been extracted, computed, and replaced back in the original string. I have used non-consuming (lookbehind/lookahead) groups so only the digits are passed to the replacement string, and the wrapping pattern is kept in the updated string.
更多推荐
发布评论