将文件中的字符串替换为列表中的字符串作为dict值

时间:2018-03-23 13:09:55

标签: python html

我有一个文件,我想在其中替换字符串,这些字符串是替换dict的值。一切都工作得很好,但是当dict的值列表时我有问题。

基本上:我在list3中有22个值,在html中有22个声明为 value3 的字符串,我想用list3中的每个值替换它们。 即:

list3 = [result1,result2,result3 ....]

第一 value3 ---> RESULT1

第二 value3 ---> RESULT2

3 value3 ---> result3

...

然后将其作为字符串保存到变量。有了这个,我只得到每个value3出现的最后一个list3值。任何想法如何改进它?

def replace_html():
    substitutes = {
        'rrrrrr': string1,
        'value2': string2,
        'value3': list3,
        'value4': string4,
        'value5': string5
    }

    with open('some_html_template.html', 'r') as fin:
        html_template = []
        for line in fin:
            raw_line = line.strip()
            for key in substitutes:
                if key == 'value3':
                    for value_list in list3:
                        raw_line = raw_line.replace("___{0}___".format(key), value_list)
                raw_line = raw_line.replace("___{0}___".format(key), substitutes[key])
            html_template.append(raw_line)
        replaced_html_template = ''.join(html_template)

    fin.close()

    return replaced_html_template 

1 个答案:

答案 0 :(得分:0)

总体思路:re.sub接受callables作为替换。 我猜这样的事情会起作用:

import re
import itertools

class container(object):
    def __init__(self, values):
        self.values = itertools.cycle(values)

    def __call__(self, value):
        # every time this instance is called, 
        # it will return the next value in the list
        return self.values.next()

SUBSTITUTES = {  # it's better not to store data in functions
    'rrrrrr': string1,  # this one will be handled normally
    'value2': string2,
    'value3': container(list3),  # now it's callable; will loop through the values
    'value4': string4,
    'value5': string5
}

def replace_html():
    with open('some_html_template.html', 'r') as fin:
        html_template = []
        for line in fin:
            raw_line = line.strip()
            for search, replacement in SUBSTITUTES.items():
                raw_line = re.sub(search, replacement, raw_line)
            html_template.append(raw_line)

        # .close() is not necessary for with clauses
        return ''.join(html_template)

我想用迭代器而不是容器类可以做得更好但我希望你明白这个想法