2013-02-07 4 views
-1

나는 파이썬에서 일부 직렬 대응 스크립트를 만들려고합니다. 템플릿이있는 파일 하나와 텍스트 테이블이있는 파일이 있습니다. 대체 소스로 텍스트 테이블을 사용하는 방법은 무엇입니까?파이썬에서 사전 데이터로 텍스트 테이블을 사용하는 방법

예 imput : 템플릿 파일 : 값

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

예상 출력을 사용자 정의 텍스트 2 개 파일입니다와

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

표.

+1

나는 당신이하려고하는 것을 이해할 수 없다. 그러나 그것이 무엇이든 그것은 틀린 것이다. 'strZamien = strZamien.replace ('$', '')'- pickle이 읽어 들일 수있는 black-boxed 바이트 스트림으로 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

수입은 당신이 당신의 테이블에 대한 SQLite는 사용하는 조언 Personaly

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 

를 다시.

+0

우리가 모든 키워드를 알고 있다면 좋겠지 만 테이블이 충분한 정보를 제공하는 한 내 스크립트는 모든 입력 테이블과 템플릿에서 작동해야한다. – sonia

관련 문제