如何更改数值并仅匹配单词作为文件内的键?

  • 本文关键字:文件 单词作 何更改 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)

我看到在大多数情况下您使用in语句来检查字符串。像这里:

if self.name in file:

或这里

if self.target in content:

我认为这不是你需要的。in语句检查一个字符串是否包含在另一个字符串中,例如'a' in 'bac'返回True。并且还count=max_count=回报True.所以问题可能从这里出现。

我想您需要检查确切的相等性,因此您应该更改这些行:

if self.name == file:

if self.target == content:

现在,要使用此解决方案,您需要将值与目标分开。使用拆分方法。

例如,如果content"count=123"您可以执行以下操作:

sepcontent = content.split('=')

这将创建一个['count', '0']sepcontent的列表。您可以在第一个元素if self.target == sepcontent[0]中检查相等性。

执行此操作时,您肯定需要逐行迭代。所以不要使用target.read(),这将创建完整文件的单个字符串。

最后,你应该有这样的东西:

wfile = 'tempfile.txt'
with open(file) as target:
with open(wfile, 'w') as wtarget:
for content in target:
sepcontent = content.split("=")
if sepcontent[0] == "count": #or your self.target
content = content.replace(spline[1], self.value)
wtarget.write(content)

最后,您将在一个名为tempfile.txt.您可以简单地重命名此文件以替换原始文件。

我并没有完全遵循您的代码,但是您主要问题的解决方案似乎是使用正则表达式。

如果字符串s = 'x_count=1ncount=0ncount_xx=0'

x_count=1
count=0
count_xx=0

您可以使用正则表达式查找和替换后面的数字count=

import re
s = 'x_count=1ncount=0ncount_xx=0'
## user inputs the number 1, so we replace the current number with 1
new_s = re.sub(r'ncount=(d)', r'ncount=1', s)

让我知道这是否有帮助!

编辑:

import re
user_input = 1
for file_name in list_of_file_names:
with open(file_name) as f:
new_file_content= re.sub(r'ncount=(d)', r'ncount=%d'(user_input), f.read())
with open(file_name, "w") as f:
f.write(new_file_content)

最新更新