2009-04-13 3 views
1

골프 - 간단한 템플릿 체계를 구현합니다.골프 - 템플릿을 텍스트 파일로 확장

확장 횟수는 다음과 같습니다

  • % 키 % -> VALUE
  • %% -> %

명령 줄 인수 :

  • ARG1 : 사전 파일 포맷 key=value 스타일 예 :
  • ARG2 : templ 먹은 파일

내 골프는 아직 시도하지 않았다. (파이썬) : 261 자.

import sys 
dd = dict([ll.split("=",2) for ll in open(sys.argv[1],'r') if len(ll.split("=", 2)) == 2]) 
tt = "".join([ ll for ll in open(sys.argv[2],'r')]) 
sys.stdout.write("".join([(((s == "") and "%") or ((s in dd) and dd[s]) or s) for s in tt.split("%")])) 

DICT

NAME=MyName 
ODDS=100 

템플릿

I, %NAME% am %ODDS% %% sure that that this a waste of time. 

결과

I, My Name am 100 % sure that this is a waste of time. 

예, 나는이 짧은과 더 나은, "스냅"결함이있는 템플릿 시스템입니다 실현 이행.

답변

2

파이썬에서는 inbuilt 문자열 형식을 사용하여 더 짧게 만들 수 있습니다. 일치시킬 구문을 얻기 위해 약간의 정규식 해킹이 필요합니다.

import sys, re 
sys.stdout.write(re.sub(r'%(.+?)%',r'%(\1)s',open(sys.argv[2]).read())%dict(l.split("=",2) for l in open(sys.argv[1],'r'))) 

최대 139 바이트. (아마도 비록 인수/파일 IO 물건은 정말 골프 도전의 일부가 될 수 없습니다해야합니까?)

1

C#.

string s = "NAME=MyName ODDS=100"; // any whitespace separates entries 
string t = "I, %NAME% am %ODDS% %% sure that that this a waste of time."; 

foreach(var p in s.Split().Select(l=>l.Split('=')).ToDictionary(
e=>"%"+e[0]+"%",e=>e[1]))t=t.Replace(p.Key,p.Value);t=t.Replace("%%","%"); 
Console.WriteLine(t); 

알고리즘 부분은 159입니다. "NAME = %%"와 같은 식으로 피드하면 (예 : %%를 %로 축소 할 예정) 예기치 않은 결과가 발생할 수 있지만 짧은 간단한 알고리즘은 이와 같은 동작을 나타냅니다. 어떤 순서로 문자열 바꾸기를 할 수 있습니다.

+0

+1 니스, 내가 그런 일을 게시하고 있었다 –

0

루비, 114 개 문자 VC에서

d=Hash[*[open(ARGV[0]).read.scan(/(.+)=(.*)/),'','%'].flatten] 
print open(ARGV[1]).read.gsub(/%([^%]*)%/){d[$1]} 
1

++ .. 가장 빠른 방법 :

수 있습니다
void customFormat(const char* format, char dicItemSep, char dicValueSep, const char* dic, char* out) 
{ 
    if(out) 
    { 
     const char x = '%'; 
     while(*format) 
     { 
      while(*format && *format != x)*out++=*format++; 
     if(!*format || !*(++format))goto exit; 
      if(*format == x) 
      { 
       *out++=x; 
       continue; 
      } 
      const char *first = format; 
      const char *d = dic; 
      while(*first) 
      { 
       while(*d) 
       { 
        while(*d && (*d != *first))d++; 
        if(*d == *first) 
        { 
         while((*first++ == *d++) && (*d != dicValueSep)); 
         if(!*first)goto exit; 
         if(*d != dicValueSep || *first != x) 
         { 
          first = format; 
          while(*d && (*d != dicItemSep))d++; 
          continue; 
         } 
         break; 
        } 
       } 
       if(!*d)break; 
       d++; 
       while((*d != dicItemSep) && *d && (*out++ = *d++)); 
       format = ++first; 
       break; 
      } 
     } 
    exit: 
     *out = 0; 
    } 
} 
int _tmain(int argc, _TCHAR* argv[]) 
{ 
    char t[1024]; 
    customFormat 
     (
      "%NAME% am %ODDS% %% sure that that this a waste of time.", 
      '\n', 
      '=', 
      "NAME=MyName\nODDS=100", 
      t 
     ); 
    printf("%s", t); 
} 
0
정말

아니 질문에 대한 답변,하지만 난 당신이 당신이 진짜 단어 작업의 모든 종류이 필요한 경우, 파이썬은 {variable}

훨씬 더 읽을 수 템플릿 형식이 실현 희망 당신이 원하는 경우
# MyDict.py 
dict = { 
    some : 'every', 
    p : '?', 
    q : '?..' 
} 

# main file 
import MyDict 
print """ 
    What is {some}thing{p} 
    Who values this mysterious {some}thing{q} 
""".format(**dict) 

, 당신이 당신의 사전 형식으로 보존 할 수 있습니다 :

with open(dictionary_file, 'r') as f: 
     for l in f.readlines(): 
      k, v = '='.split(l) 
      if v: dict[k] = v