Python打印全文fi

2024-04-16 13:27:19 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我该怎么做?你知道吗

文本文件1.txt

user1
user2

文本文件2.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

目标:

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

Tags: httpspostxtcomurlexampletagwww
1条回答
网友
1楼 · 发布于 2024-04-16 13:27:19

以下是我的解决方案:

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

相关问题 更多 >