gpt4 book ai didi

python - 使用通配符搜索和替换文本文件中的字符串

转载 作者:太空宇宙 更新时间:2023-11-04 09:17:18 27 4
gpt4 key购买 nike

尝试在 python 中对文本文件的内容使用通配符进行搜索/替换:

如果文本文件的内容是这样的:

"all_bcar_v0038.ma";"all_bcar_v0002.ma";"all_bcar_v0011.ma";"all_bcar_v0011.ma";

Looking to replace all the version numbers with v1000 to get this:

"all_bcar_v1000.ma";"all_bcar_v1000.ma";"all_bcar_v1000.ma";"all_bcar_v1000.ma";

And have the file written out.

I've tried the below but what happens is the script only catches the first version number, leaving the others untouched:

def replaceAll(file,searchExp,replaceExp):
for line in fileinput.input(file, inplace=1):
if searchExp in line:
line = line.replace(searchExp,replaceExp)
sys.stdout.write(line)

rigs = ['all_bcar']
rigs_latest = ['all_bcar_v1000']

old_pattern = []
old_compiled = []
old = []
old_version = []

for rig in range(len(rigs)):
old_pattern.append("/" + rigs[rig] + "_(.*).ma")
fin = open(txt_file, "r")

old_compiled.append(re.compile(old_pattern[rig]))
old.append(old_compiled[rig].search(fin.read()))
old_version.append(old[rig].group(1).strip())
old_rig = (rigs[rig] + "_" + old_version[rig])
replaceAll(txt_file,old_rig,rigs_latest[rig])


fin.close()

不确定如何保持搜索循环以查找其他版本并避免已经被替换的版本,以跳过等于“v1000”的任何版本。

最佳答案

使用 regexes 将大大改善您的生活.您应该能够在两行中完成此操作(假设我正确理解了问题):

import re

for line in fileinput.input(file, inplace=1):
re.sub(r"_v\d{4}", "_v1000", line)

关于python - 使用通配符搜索和替换文本文件中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7601820/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com