python - 如何更改数值并仅匹配单词作为文件中的键?
问题描述
我是 python 新手,正在尝试制作一个简单的配置编辑器应用程序。
我有一个.txt
文件,其中包含一堆单词,count
例如:
...
...
max_count=1000
count=123
host_count=000
...
...
在我的情况下,我只想更改与count=
作为键的确切单词匹配的count=0
任何数字(在=
符号之后),我希望它被用户从输入字段中给出的值替换,同时忽略其他计数喜欢max_count=, host_count=, etc
。有可能这样做吗?
例如:
当用户在输入字段中输入 0 时,结果将是
count=0
当用户在输入字段中输入 1 时,结果将是
count=1
另一个
xxx_count=
或count_xxx=
将被忽略
我试着像下面那样做,但是所有的计数都被替换了,而不仅仅是count=
它自己的匹配词。
files = Finder(self.path, self.name).find()
for file in files:
with open(file) as target:
content = target.read()
if self.target in content:
print(content)
content = content.replace(self.target, self.value)
with open(file, "w") as target:
target.write(content)
else:
print('{} not found in {}'.format(self.target, file))
请帮忙。
更新
这是我的 Finder 类(它仅用于查找文件)。
import os
class Finder:
result = []
"""
Create new instance.
:param {string} path: the directory of the target file.
:param {string} name: the name of the file.
"""
def __init__(self, path, name):
self.path = path
self.name = name
# Find files in the given path.
def find(self):
directory_exists = os.path.isdir(self.path)
if not directory_exists:
return print('Tidak dapat menemukan file {} di folder: {}.'.format(self.name, self.path))
for root, dirs, files in os.walk(self.path):
for file in files:
if self.name in file:
self.result.append(os.path.join(root, file))
return self.result
这是我的Modifier
课程的完整版本:
from modules.Finder import Finder
from pprint import pprint
class Modifier(Finder):
"""
Create new instance.
:param target: target to be modified.
:param value: value to be used on target.
"""
def __init__(self, path, name, target, value):
self.target = target
self.value = value
Finder.__init__(self, path, name)
def modify(self):
files = Finder(self.path, self.name).find()
if not files:
return files
for file in files:
with open(file) as target:
content = target.read()
if self.target in content:
print(content)
content = content.replace(self.target, self.value)
with open(file, "w") as target:
target.write(content)
else:
print('{} not found in {}'.format(self.target, file))
更新 2
只是为了确保每个人都明白我想做什么。这是我App.py
控制程序的文件。
from pprint import pprint
from modules.Modifier import Modifier
SMSGW = Modifier('D:\\Smsgw', 'SMSGW.ini', 'count=', 'count=0')
settings = SMSGW.modify()
pprint(settings)
解决方案
使用正则表达式^count=\d+$
替换完全匹配count=somenumber
考虑:
user_input
是用户输入的输入,content
是从文件中读取的数据
import re
re.sub(r'^count=\d+$', 'count={}'.format(user_input), content)
推荐阅读
- javascript - 如何使用 PHP ajax 在模态框中提交 HTML 表单数据?
- python - Matplotlib - 如何从任何条形的顶部到 y 轴画一条线?
- php - 将变量从控制器传递到视图时,Codeigniter form_open() 加载视图文件两次
- python - 如何在 Django 中从 MultiValueDict 读取或保存文件
- python - 如何使用 numpy 加载读取 zip 文件中的 npz 文件
- java - 判断api请求是来自CURL还是POSTMAN?
- jquery - 使用 Jquery 在单击时选择列表中的下一个元素
- python - 在 Python 中绘制有向图?
- javascript - 如何为 vanilla-lazyload 动态设置图像高度和宽度
- node.js - Mongoose findByIdAndUpdate 销毁缺失的字段