Python 替换文本值正则表达式
Python replace text value regular expression
是否可以仅替换文件中特定文本的值 python?下面的代码替换了字符串,但是我找不到只替换 project_id 或 project_name 的值的方法。
import re
def replace():
with open("/Users/test/file.txt", "r") as sources:
lines = sources.readlines()
with open("/Users/test/file.txt", "w") as sources:
for line in lines:
sources.write(re.sub(r"Settings", 'Project_settings', line))
replace()
file.txt
Settings
######################
project_id = "468324678997"
project_name = "test"
输出:
Project_settings
######################
project_id = "468324678997"
project_name = "test"
我想将 project_name 的值替换为“abc”
期望的输出:
file.txt
Settings
######################
project_id = "468324678997"
project_name = "abc"
我建议使用配置覆盖字典,而不是正则表达式
这样,您就不会意外地替换所有匹配的文本
def replace(file, overrides):
with open(file, "r") as sources:
lines = sources.readlines()
with open(file, "w") as sources:
# skip the header rows
next(lines)
next(lines)
for line in lines:
config_key = line.split(' = ')[0]
if config_key in overrides:
sources.write('{} = {}\n'.format(config_key, overrides[config_key]))
overrides = {
'project_name': 'abc'
}
replace("/Users/test/file.txt", overrides)
可能有更好的 Python 库可以读取 属性 文件并允许您覆盖特定值
自动化 text-editor 的 regex-replace
我用 任意格式 text-file.
替换每个匹配行的秘诀
作为 re.sub
的参数
你可以使用一对 regular-expressions:pattern-to-match 和 replacement,比如 regex-tuple (r'^Settings', r'Project_settings')
.
存储这些的数据结构可以是元组(对)列表,例如replacements
。
import re
replacements = [
('^Settings', 'Project_settings'),
(r'^project_name = "(.*)"', r'project_name = "abc"'), # simply replaces with fixed value
(r'^project_id = "(.*)"', r'project_id = "P-"') # copies in the found group 1 at
]
def replace():
lines = []
with open("project_properties.cfg", "r") as config:
for line in config.readlines():
for pair in replacements: # apply each replacement that matches line
line = re.sub(pair[0], pair[1], line) # substitute found pattern with replacement
lines.append(line) # add each read line to the buffer (if changed or not)
with open("project_properties_.cfg", "w") as config: # Note: used a new filename
config.writelines(lines)
replace()
将产生所需的输出(在 project_id
处加上 inserting-replacement):
Project_settings
######################
project_id = "P-468324678997"
project_name = "abc"
使用现有库进行解析和更新
作为OneCricketeer's answer suggests:
当您设法忽略 header 时,您将认识到 与至少两个常见 config-file 的强相似性(即 key = value
表示) ] 格式:
这将允许您研究和查找现有库,例如 Python 的 built-in configparser:
是否可以仅替换文件中特定文本的值 python?下面的代码替换了字符串,但是我找不到只替换 project_id 或 project_name 的值的方法。
import re
def replace():
with open("/Users/test/file.txt", "r") as sources:
lines = sources.readlines()
with open("/Users/test/file.txt", "w") as sources:
for line in lines:
sources.write(re.sub(r"Settings", 'Project_settings', line))
replace()
file.txt
Settings
######################
project_id = "468324678997"
project_name = "test"
输出:
Project_settings
######################
project_id = "468324678997"
project_name = "test"
我想将 project_name 的值替换为“abc”
期望的输出: file.txt
Settings
######################
project_id = "468324678997"
project_name = "abc"
我建议使用配置覆盖字典,而不是正则表达式
这样,您就不会意外地替换所有匹配的文本
def replace(file, overrides):
with open(file, "r") as sources:
lines = sources.readlines()
with open(file, "w") as sources:
# skip the header rows
next(lines)
next(lines)
for line in lines:
config_key = line.split(' = ')[0]
if config_key in overrides:
sources.write('{} = {}\n'.format(config_key, overrides[config_key]))
overrides = {
'project_name': 'abc'
}
replace("/Users/test/file.txt", overrides)
可能有更好的 Python 库可以读取 属性 文件并允许您覆盖特定值
自动化 text-editor 的 regex-replace
我用 任意格式 text-file.
替换每个匹配行的秘诀作为 re.sub
的参数
你可以使用一对 regular-expressions:pattern-to-match 和 replacement,比如 regex-tuple (r'^Settings', r'Project_settings')
.
存储这些的数据结构可以是元组(对)列表,例如replacements
。
import re
replacements = [
('^Settings', 'Project_settings'),
(r'^project_name = "(.*)"', r'project_name = "abc"'), # simply replaces with fixed value
(r'^project_id = "(.*)"', r'project_id = "P-"') # copies in the found group 1 at
]
def replace():
lines = []
with open("project_properties.cfg", "r") as config:
for line in config.readlines():
for pair in replacements: # apply each replacement that matches line
line = re.sub(pair[0], pair[1], line) # substitute found pattern with replacement
lines.append(line) # add each read line to the buffer (if changed or not)
with open("project_properties_.cfg", "w") as config: # Note: used a new filename
config.writelines(lines)
replace()
将产生所需的输出(在 project_id
处加上 inserting-replacement):
Project_settings
######################
project_id = "P-468324678997"
project_name = "abc"
使用现有库进行解析和更新
作为OneCricketeer's answer suggests:
当您设法忽略 header 时,您将认识到 与至少两个常见 config-file 的强相似性(即 key = value
表示) ] 格式:
这将允许您研究和查找现有库,例如 Python 的 built-in configparser: