我怎么能合并2个.text文件?

时间:2015-04-05 21:34:12

标签: python python-3.x

我有2个.txt文件,如下所示:

letter.txt:

[fname] [lname]
[street]
[city]

Dear [fname]:

   As a fellow citizen of [city], you and all your neighbours 
on [street] are invited to a celebration this Saturday at 
[city]'s Central Park. Bring beer and food!

q2.txt:

Michael

dawn

lock hart ln

Dublin

--

kate

Nan

webster st

king city

--

raj

zakjg

late Road

Toronto

--

dave

porter

Rock Ave

nobleton

--

John

Doe

round road

schomberg

如何合并文件以生成和打印个性化字母,例如第一个地址应打印:

迈克尔

黎明

锁定hart ln

都柏林

亲爱的迈克尔:

作为都柏林的同胞,你和你所有的邻居 关于锁定hart ln被邀请参加本周六的庆祝活动 都柏林中央公园。带上啤酒和食物!

总之:我如何创建一个函数来合并这些2.txt文件来制作个性化的字母?

到目前为止:

first_file = open( "letter.txt", "r")

dest_file = open( "q2.txt", 'w')

for line in first_file:

    v=line.split()

    for x in v:

        if x[0]=="fname":

            dest_file.write(x+"\n")


first_file.close()

dest_file.close()

3 个答案:

答案 0 :(得分:4)

一旦您了解了如何从第二个文件中读取变量,您就可以通过多种方式在模板中替换它们。最简单的方法是将.format() method与变量一起使用。在模板中,您可以通过添加{fname}并在.format()方法中将其添加为变量来定义标记。

实施例

"""{fname} {lname}
{street}
{city}

Dear {fname},

   As a fellow citizen of {city}, you and all your neighbours 
on {street} are invited to a celebration this Saturday at 
{city}'s Central Park. Bring beer and food!""".format(fname='John', lname='Doe', street='Main St', city='Anywhere')

输出:

John Doe
Main St
Anywhere

Dear John,

   As a fellow citizen of Anywhere, you and all your neighbours
on Main St are invited to a celebration this Saturday at
Anywhere's Central Park. Bring beer and food!

答案 1 :(得分:2)

阅读以下文件:

letter = ''
q2 = ''

with open('letter.txt', 'r') as f:
    letter = f.read()
f.close()

with open('q2.txt', 'r') as f:
    q2 = f.read()
f.close()

然后定义一些函数:

def cleanData(query):
 return [item.strip().split('\n\n') for item in query.split('--')]

def writeLetter(template, variables, replacements):
    # replace ith variable with ith replacement variable
    for i in range(len(variables)):
         template = template.replace(variables[i], replacements[i]) 
    return template

然后:

variables = ['[fname]', '[lname]', '[street]', '[city]']
letters = [writeLetter(letter, variables, person) for person in cleanData(q2)]

这是[编辑:更新] ipython notebook

答案 2 :(得分:1)

试试这个。我想最丑陋的方式。请等待好的答案。

with open('AdressFile.txt') as f: #assuming as a large file
    for i in f:
        fname = i
        next(f,None) #skipping \n
        lname = next(f,None)
        next(f,None)   #skipping \n
        street = next(f,None)
        next(f,None)  #skipping \n
        city = next(f,None)
        next(f,None)   #skipping \n
        next(f,None)    #skipping -----
        next(f,None)    #skipping \n

        with open('letterFile.txt') as f1: 
            temp = f1.read() # assuming as a small file
            temp = temp.replace('[fname]',fname.strip())
            temp = temp.replace('[lname]',lname.strip())
            temp = temp.replace('[city]',city.strip())
            temp = temp.replace('[street]',street.strip())
        print(temp)

#output
Michael dawn
lock hart ln
Dublin

Dear Michael:

   As a fellow citizen of Dublin, you and all your neighbours 
on lock hart ln are invited to a celebration this Saturday at 
Dublin's Central Park. Bring beer and food!

......