在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問(wèn)答/Java  Python/ 如何匹配一短文本中雙引號(hào)內(nèi)的一個(gè)單詞或字符串,之后在寫(xiě)回原位置???

如何匹配一短文本中雙引號(hào)內(nèi)的一個(gè)單詞或字符串,之后在寫(xiě)回原位置???

我只想替換引號(hào)內(nèi) SQL 語(yǔ)句的 as, 而不影響引號(hào)外部的,下面是我的代碼,能匹配到,也能在控制臺(tái)顯示替換了,但就是沒(méi)法回寫(xiě)到文本里:

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)

上面這段程序也確實(shí)替換了,findall 把引號(hào)中的內(nèi)容都獲取了,替換后控制臺(tái)也打印出來(lái)了,但是怎么寫(xiě)回到源文件的原位置啊,求大神指點(diǎn)?

----- (編按: 下方是原問(wèn)者在評(píng)論中的補(bǔ)充)

感謝你的答案。我的方法已經(jīng)能替換掉,重點(diǎn)是:

我想把替換后的結(jié)果寫(xiě)回源文件里面下面是我的代碼。

我需要處理的是一堆文件夾里的一些 .txt 文本中,雙引號(hào)里的某幾個(gè)關(guān)鍵字,例如 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()
回答
編輯回答
不歸路

借助一個(gè)函數(shù)來(lái)實(shí)現(xiàn)替換的操作

import re

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

# 替換函數(shù),參數(shù)是一個(gè)Match對(duì)象,返回值是替換的結(jié)果。 
def repl(m):
    return '"' + m.group(1) + "bas" + m.group(2) +'"'

print p.sub(repl, Str)

運(yùn)行結(jié)果:

for(x as m){
       "select t.id bas t from user;"        
       }
       
      for( z as C)
2018年4月21日 17:27