2011-10-15 4 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을 사용했습니다.