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

标签 python regex

尝试在 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/

相关文章:

python - 根据另一个数据帧的值更新数据帧

PHP:替换字符串中所有出现的 "[CODE]...[/CODE]"

python - 从字符串中删除\u?

正则表达式 - 匹配主题标签之外的子字符串(#)

python - 将字符串数组中的元素输出到句子

python - 如何在 Python 中读取整个文件?在命令行中普遍工作

需要 Python 2.6 版,在注册表中找不到

python - 计算 3D(或 n-D)质心的最佳方法是什么?

php - 正则表达式:如何匹配字符串中的最后一个点

python - 用 Pandas 快速删除标点符号