2013-02-07 29 views
-1

我想在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

我不知道你在做什麼 - 但不管它是什麼,這是錯誤的。你不應該試圖操縱pickle數據的結果 - 就像你在行上做的那樣'strZamien = strZamien.replace('$','')' - 將pickle數據視爲黑盒字節流,pickle可以讀回您。 – jsbueno

+1

您能否提供一些簡單的示例,說明您希望爲某些示例輸入輸出什麼內容?我無法弄清楚你想做什麼。 –

+0

我認爲這個問題的答案可能對某人有用,編輯它會更精確。考慮重新打開它? – sonia

回答

2

這有兩個部分。首先是解析您的文本表以獲取模板佔位符的映射列表到需要插入的值。第二個是實際將值替換爲模板。兩者都相當簡單。

假設列在表格中由多個空格分隔,並且多個空格永遠不會構成實際列標題或值的一部分,那麼可以使用regular expressions將每一行很容易且乾淨地拆分爲字段,然後替換將這些值放入模板中是微不足道的。

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爲您的值替換爲模板,使代碼更簡單。

+0

這就是我正在尋找的,謝謝:) – sonia

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 

本人來說我建議你使用SQLite,讓你的餐桌。

+0

如果我們知道所有的關鍵字,但是我的腳本應該適用於任何輸入表和模板,只要表格提供了足夠的信息 – sonia

相關問題