首页 > 解决方案 > 在Python3中的许多文档中增加子字符串中的数值

问题描述

我有一个项目,我需要从多个文件中找到票证密钥,并将数字部分增加给定的数量。假设是 3000。所以 FOOBAR-123 将是 FOOBAR-3123。文件的其余内容应保持不变。

根据我在这里和论坛上的原始问题的提示,我有一些可行的方法,但我希望它更强大。也许在我编辑它们之前保存原始文件。或者避免我不想修改的东西,比如称为“UTF-8”的子字符串。

人们要求提供我要解析的文本样本。我想要一些可以对任何格式的文本文件进行转换的东西。XML、json 等。没关系。但我确实想确保修改后的文件只被递增的子字符串修改,否则保持不变。我注意到如果我多次运行我的脚本,它就会停止可靠地工作(从某种意义上说,它错过了第一个子字符串......我认为我需要修改一些东西以便在换行/回车方面更智能?)

这是我到目前为止所拥有的:

import re
import sys
import os

increment_val = 3000

def increment_me(match_obj):
  if match_obj.group() is not None:
    (key, num) = match_obj.group(1).split('-')
    return key + '-' + str(int(num) + increment_val)

for file in os.listdir(sys.argv[1]):
  with open(file, 'r') as fh:
    file_string = fh.read()
    fh.close()
    # This line just to test regex
    #number_match = re.findall(r"\W(\w+\-\d+)\W", file_string)
    file_string = re.sub(r"\W(\w+\-\d+)\W", increment_me, file_string)
    fh = open(file, 'w')
    fh.write(file_string)
    fh.close()

任何让它变得更好的提示都非常感谢!例如,我注意到我的脚本将匹配包含多个破折号的内容。

标签: python-3.x

解决方案


我认为做你想做的最干净的方法是通过多个步骤。尝试以下操作:

import regex  # check https://pypi.org/project/regex/

# example of a match found, given your example
text = 'FOOBAR-123'

# match a number if what comes before it is a dash
# and what comes after is the end of the string
number_match = regex.search('(?<=\p{Pd}\s?)(?P<value>\d+)(?=$)', text)

# increments the number found in the string
number_incremented = regex.sub(r'(?<=\p{Pd}\s?)\d+(?=$)', str(int(number_match.group('value')) + 3000), text)

# now number_incremented is 'FOOBAR-3123'

看看https://docs.python.org/3/library/re.html#re.sub


推荐阅读