简体   繁体   English

Python打印全文文件

[英]Python print full text file

I want to replace the word "example" on textfile2.txt with a list of words from textfile1.txt until the list runs out or all the "example" have all been replaced then I want to display the whole finished text. 我想用textfile1.txt中的单词列表替换textfile2.txt上的单词“example”,直到列表用完或所有“示例”全部被替换,然后我想显示整个完成的文本。

How would I do this? 我该怎么做?

textfile1.txt textfile1.txt

user1
user2

textfile2.txt 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

Current code: 当前代码:

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)

Results it gives me: 结果它给了我:

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

user2

Goal: 目标:

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

here is the my solution: 这是我的解决方案:

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"

updated: this need import itertools 更新:这需要导入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" 

output: 输出:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM