如何匹配一短文本中双引号内的一个单词或字符串,之后在写回原位置???

我只想替换引号内 SQL 语句的 as, 而不影响引号外部的,下面是我的代码,能匹配到,也能在控制台显示替换了,但就是没法回写到文本里:

Str = ''' for(x as m){
       "select t.id as t from user;"        
       }
       
      for( z as C)
       '''
       
m = re.findall('\"(.*?)(?<![^\\\\]\\\\)\"', Str, re.S)

for item in m :
    rs = re.sub('as', 'bas', item)
    print(rs)

上面这段程序也确实替换了,findall 把引号中的内容都获取了,替换后控制台也打印出来了,但是怎么写回到源文件的原位置啊,求大神指点?

----- (編按: 下方是原問者在評論中的補充)

感谢你的答案。我的方法已经能替换掉,重点是:

我想把替换后的结果写回源文件里面下面是我的代码。

我需要处理的是一堆文件夹里的一些 .txt 文本中,双引号里的某几个关键字,例如 select as,change 等。

import re, codecs, os

def scan_files(directory, prefix=None, postfix=None):
    files_list = []
    for root, sub_dirs, files in os.walk(directory):
        for special_file in files:
            if postfix:
                if special_file.endswith(postfix):
                    files_list.append(os.path.join(root, special_file))
                    # print "i scan the file is:"+special_file +"\n"
            elif prefix:
                if special_file.startswith(prefix):
                    files_list.append(os.path.join(root, special_file))
            else:
                files_list.append(os.path.join(root, special_file))
    return files_list

def replace1(result):
    str = 'z90'
    return str + result.group(1) + result.group(2)

def str_replace(files):
    i = 0
    for eachXLF in files:
        i += 1
        # if eachXLF.endswith('.php'):
        # i += 1
        print(i)
        print("i scaned file is:" + eachXLF + "\n")
        # print ( "open"+ i +"files:"+ eachXLF + "\n" )
        openXLF = codecs.open(eachXLF, 'r+b', encoding='utf-8', errors='ignore')
        XLF = openXLF.read()

        m = re.findall('\"(.*?)(?<![^\\\\]\\\\)\"',XLF,re.S)
        for item in m :
            rs = re.sub('^SELECT','aaSELECT',item)
            ri = re.sub('FROM','aaFROM',rs)
            print(ri)
    
        openXLF.seek(0)
        openXLF.write(XLF)
        openXLF.truncate()
        # print(XLF)
        openXLF.close()

def main():
    path = 'E:/Pythons/uploads'
    str_replace(scan_files(path, prefix=None, postfix='.txt'))


if name == '__main__':
    main()
阅读 3.9k
1 个回答

借助一个函数来实现替换的操作

import re

Str = ''' for(x as m){
       "select t.id as t from user;"        
       }
       
      for( z as C)
       '''
p = re.compile('\"(.*?)as(.*?)\"') 

# 替换函数,参数是一个Match对象,返回值是替换的结果。 
def repl(m):
    return '"' + m.group(1) + "bas" + m.group(2) +'"'

print p.sub(repl, Str)

运行结果:

for(x as m){
       "select t.id bas t from user;"        
       }
       
      for( z as C)
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题