2011-10-15 115 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使混洗命令列表重复无限次。