python-3.x - 在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()
任何让它变得更好的提示都非常感谢!例如,我注意到我的脚本将匹配包含多个破折号的内容。
解决方案
我认为做你想做的最干净的方法是通过多个步骤。尝试以下操作:
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'
推荐阅读
- python - 如何处理烧瓶 URL 应用程序中的特殊字符?
- elasticsearch - Elasticsearch 中的多匹配查询和评分计算
- python - 解析字符串列表并根据这些字符串的切片返回连接字符串的最佳方法是什么?
- node.js - 无轮询的无尽滚动(实时)
- python - 如何使用 Selenium WebDriver Python 读取在浏览器中打开的 PDF 文件?
- reactjs - React 如何在 useEffect 之外清理 setTimeout
- spring - VSCODE:java.lang.ClassNotFoundException:org.springframework.web.servlet.DispatcherServlet
- python - 通过 Python 在 Redshift 中创建表的问题
- mysql - SQL 从同一个表中的一组值中选择不同的值
- unity3d - 在 Update() 中 SetActive 可以吗?