2011-10-15 84 views
0

我有兩個開源文件我一直在搞亂,一個文件是我正在使用的一個小宏腳本,第二個是充滿命令的txt文件我想在各自的行內以隨機順序插入第一個腳本。我設法想出了這個腳本來搜索和替換這些值,但是不要從第二個txt文件中隨機地插入它們。Python - 隨機替換文本中的值

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) 

replaceAll('C:/Users/USERACCOUNT/test/test.js','InterSearchHere', RandomValueFrom2ndTXT) 

任何幫助,如果非常感謝!提前致謝!

回答

1
import random 
import itertools as it 

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

with open('SecondFile','r') as f: 
    replaceExp=f.read().splitlines() 
random.shuffle(replaceExps)   # randomize the order of the commands 
replaceExps=it.cycle(replaceExps) # so you can call `next(replaceExps)` 

replaceAll('C:/Users/USERACCOUNT/test/test.js','InterSearchHere', replaceExps) 

每當您撥打next(replaceExps)時,您會從第二個文件中獲得不同的行。

當有限迭代器耗盡時,next(replaceExps)將引發StopIteration異常。爲了防止這種情況發生,我使用itertools.cycle使混洗命令列表重複無限次。