-1

我正在尝试在 python 中制作一些串行通信脚本。我有一个带有模板的文件,一个带有文本表的文件。如何使用文本表作为替换源?

示例输入:模板文件:

Hello <name>,
We will be hosting some event in <town> bla bla...

带值的表

name      town       age   gender
Phillip   New York   22    male
Sonia     Warsaw     19    female

预期输出是 2 个带有自定义文本的文件。

4

2 回答 2

2

这有两个部分。首先是解析您的文本表以获取模板占位符到需要插入的值的映射列表。第二个是将值实际替换到模板中。两者都相当容易。

假设表中的列由多个空格分隔,并且多个空格从不构成实际列标题或值的一部分,您可以使用正则表达式将每一行相当容易和干净地拆分为字段,然后替换这些值进入模板是微不足道的。

import re

text_table = <something> # Replace with whatever you do to load the table
template_text = <something> # Replace with whatever you do to load the template

row_splitter = re.compile("  +") # Finds a sequence of two or more spaces
rows = text_table.split('\n') # Split the table into a list of rows
headings_row = rows[0]
headings = row_splitter.split(headings_row)

# Next we get a list of dictionaries mapping template placeholders to values
template_dicts = []
for row in rows:
    values = row_splitter.split(row)
    template_dict = dict(zip(headings, values))
    template_dicts.append(template_dict)

# Next we substitute the values sets into the template one by one:
for template_dict in template_dicts:
    result_text = template_text
    for key, value in template_dict.iteritems():
        result_text = result_text.replace('<'+key+'>', value)
    print result_text # Or do whatever you like with it

请注意,如果您可以控制模板文件,您可能希望将三角括号占位符替换为大括号占位符(如'Hello {name}, I see you are {age} years old')。然后,您可以使用String.format为您将值替换到模板中,从而使代码更加简单。

于 2013-02-07T21:24:09.673 回答
1

重新进口

table_lines = open('your_table', 'r').read()
table = [ re.split(' +', l) for l in table_file[1:] ]

mail = open('your_template_dir', 'r').read()

for name,town,age,gender in table :
    re.sub('<name>', name, mail)
    re.sub('<town>', town, mail)
    re.sub('<age>', age, mail)
    re.sub('<gender>', gender, mail)

print mail

Personaly 我建议您使用 SQLite 作为您的表。

于 2013-02-07T22:33:04.217 回答