【问题标题】:Python - Replace Value in Text at RandomPython - 随机替换文本中的值
【发布时间】:2011-10-15 20:08:31
【问题描述】:

我有两个我一直在搞乱的开源文件,一个文件是我正在使用的一个小宏脚本,第二个是一个 txt 文件,其中包含我想插入到第一个脚本中的命令各自行内的随机顺序。我设法想出了这个脚本来搜索和替换值,但不是从第二个 txt 文件中以随机顺序插入它们。

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)

任何帮助,如果不胜感激!提前致谢!

【问题讨论】:

    标签: python search random replace


    【解决方案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 让洗牌后的命令列表无限重复。

    【讨论】:

      猜你喜欢
      • 2012-05-18
      • 1970-01-01
      • 2018-05-21
      • 1970-01-01
      • 1970-01-01
      • 2018-04-03
      • 2017-09-18
      • 1970-01-01
      • 2012-08-15
      相关资源
      最近更新 更多