如何在Python中将文本表作为字典数据使用
我正在尝试用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 个回答
1
首先,导入一个叫做re的库,这个库可以帮助我们处理文本,比如查找和替换内容。
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
我个人建议你使用SQLite来管理你的数据表。
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来帮你把值替换到模板中,这样代码会更简单。