Python打印全文文件

Python打印全文文件,python,replace,text-files,Python,Replace,Text Files,我想用textfile1.txt中的单词列表替换textfile2.txt中的单词“example”,直到列表用完或所有“example”都被替换,然后我想显示完整的文本 我该怎么做 textfile1.txt user1 user2 textfile2.txt URL GOTO=https://www.url.com/example TAG POS=1 TYPE=BUTTON ATTR=TXT:Follow URL GOTO=https://www.url.com/example TAG

我想用textfile1.txt中的单词列表替换textfile2.txt中的单词“example”,直到列表用完或所有“example”都被替换,然后我想显示完整的文本

我该怎么做

textfile1.txt

user1
user2
textfile2.txt

URL GOTO=https://www.url.com/example
TAG POS=1 TYPE=BUTTON ATTR=TXT:Follow

URL GOTO=https://www.url.com/example
TAG POS=1 TYPE=BUTTON ATTR=TXT:Follow
当前代码:

with open('textfile1.txt') as f1, open('textfile2.txt') as f2:
    for l, r in zip(f1, f2):
        print(r[:r.find('/example') + 1] + l)
结果它给了我:

URL GOTO=https://www.instagram.com/user1

user2
目标:


以下是我的解决方案:

with open('t1.txt') as f1, open('t2.txt') as f2:
    url_info = f2.read().split('\n\n')
    users = f1.read().split('\n')
    zipped_list = zip(users, url_info)
    for item in zipped_list:
        print item[1].replace('example', item[0])+"\n"
更新: 这需要导入itertools

import itertools
with open('t1.txt') as f1, open('t2.txt') as f2:
    url_info = f2.read().split('\n\n')
    users = [u for u in f1.read().split('\n') if u]
    zipped_list = list(itertools.izip(url_info, itertools.cycle(users)))    
    for item in zipped_list:        
        print item[0].replace('example', item[1])+"\n" 
输出:

URL GOTO=https://www.url.com/user1
TAG POS=1 TYPE=BUTTON ATTR=TXT:Follow

URL GOTO=https://www.url.com/user2
TAG POS=1 TYPE=BUTTON ATTR=TXT:Follow

URL GOTO=https://www.url.com/user1
TAG POS=1 TYPE=BUTTON ATTR=TXT:Follow

一个列表用完后,Zip将立即终止。因此,1个文件中的2行和第2个文件中的5行表示2次通过。其中只有一个会根据您的需要进行替换。第2行找不到示例,因此返回f1的第2行。如果textfile2中出现“示例”的次数大于textfile1中的字数,则此操作将无法正常工作。问题是,我想用textfile1.txt中的单词列表替换textfile2.txt中的单词“example”,直到列表用完或所有“example”都被替换,然后我想显示完整的文本。
URL GOTO=https://www.url.com/user1
TAG POS=1 TYPE=BUTTON ATTR=TXT:Follow

URL GOTO=https://www.url.com/user2
TAG POS=1 TYPE=BUTTON ATTR=TXT:Follow

URL GOTO=https://www.url.com/user1
TAG POS=1 TYPE=BUTTON ATTR=TXT:Follow