gpt4 book ai didi

Python打印全文文件

转载 作者:行者123 更新时间:2023-11-30 22:55:26 25 4
gpt4 key购买 nike

我想用 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

目标:

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

最佳答案

这是我的解决方案:

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

关于Python打印全文文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37426345/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com