2016-05-08 2 views
0

とテキストのコピーは、私は、この生のソーステキストファイルだ:のpython3:いくつかの変更

Hello {Jane Peter}, 
I send a email to your address {[email protected] [email protected]}. 

をそして私は一人一人のために、このファイルの2つのコピーを作成する必要があります。 は(アイテムが同じインデックスを持っている - ジェーン中を} {最初は、第{})

Hello Jane, 
I send a email to your address [email protected] 

2つ目に[email protected]するためのものである:

Hello Peter, 
I send a email to your address [email protected] 

したがって、{}から項目を選択し、{}全体を{}で選択してソーステキストの正しいコピー数を選択して作成することが重要です。

答えて

0

あなたは、次のコードを使用することができます。

import re 

s = '''Hello {Jane Peter}, 
I send a email to your address {[email protected] [email protected]}.''' 

count = re.search('{(.*?)}', s).group(1).count(' ') 
for i in range(count + 1): 
    print(re.sub('{(.*?)}', lambda x: x.group(1).split()[i], s)) 

出力:

Hello Jane, 
I send a email to your address [email protected] 
Hello Peter, 
I send a email to your address [email protected] 

それは、まず、第1のグループを見つけるためにre.searchを使用するには、交換し、その後に試合にスペースをカウントします作成する必要のあるコピーの数を把握します。これはもちろん、テンプレートで使用される文字列にスペースが含まれていない場合にのみ機能します。必要なコピーの数がすでに分かっている場合、これはスキップできます。

次のコードでは、re.subを使用してループ内でコピーを生成します。 {(.*?)}は、置換が必要なすべてのトークンと一致し、角カッコで囲まれたテキストをキャプチャします。次に、キャプチャされたテキストを分割し、現在処理中のインデックスにあるアイテムを使用します。

例はこの特定のシナリオでは機能しますが、この種のタスクでは実際のテンプレートライブラリを確認することをお勧めします。 Jinja2は人気のあるオプションです。

あなたが、プレースホルダから名前/電子メールを取得するために Formatter.parseを使用することができます
0

この正規表現を使用して角括弧をマッチングし、リストをたどり、必要な文字列を生成します。

import re 
matches = re.findall(r'\{([^}]+)\}', s) 
# you should verify that matches indeed contains two elements 
names = matches[0].split() 
mails = matches[1].split() 
0

from string import Formatter 

s = """Hello {Jane Peter}, 
I send a email to your address {[email protected] [email protected]}.""" 

names, emails = (p for _, p, _, s in Formatter().parse(s) if p) 
s = s.replace(names,"").replace(emails,"") 

for name, email in zip(names.split(), emails.split()): 
    print(s.format(name, email)) 

出力:

Hello Jane, 
I send a email to your address [email protected] 
Hello Peter, 
I send a email to your address [email protected] 
関連する問題