简体   繁体   English

Python搜索文本文件和替换

[英]Python Search text file & replace

I want to take a list of words from textfile1.txt and replace the word "example" on textfile2.txt to whatever the text is on line one, line two and so on.. How would I do this? 我想从textfile1.txt中获取一个单词列表,并将textfile2.txt上的单词“example”替换为第一行,第二行等文本的内容。我将如何做到这一点?

Text file textfile1.txt 文本文件textfile1.txt

user1
user2
user3
user4
user5

Text file textfile2.txt 文本文件textfile2.txt

url/example
url/example
url/example
url/example
url/example

What I have so far 到目前为止我有什么

#!/usr/bin/env python3
import fileinput

with fileinput.FileInput("textfile2.txt", inplace=True ) as file:
    for line in file:
        print(line.replace("example", "user1"), end='')

My goal: 我的目标:

url/user1
url/user2
url/user3

This should do it. 这应该做到这一点。 In general, when you want to traverse 2 or more iterables (lists, files, etc) in parallel, odds are you can use zip . 通常,当您想要并行遍历2个或更多个iterables(列表,文件等)时,您可以使用zip

with open('textfile1.txt') as f1, open('textfile2.txt') as f2:
    for l, r in zip(f1, f2):
        print(r[:r.find('/')+1] + l)

I would open the first file and read each line into an array: ['user1', 'user2', ...] 我会打开第一个文件并将每行读入一个数组: ['user1', 'user2', ...]

Then, as you read the 2nd file, keep track of your line number. 然后,当您阅读第二个文件时,请跟踪您的行号。 Index into the array based on the line number and use that string as your replacement string. 根据行号索引到数组中,并使用该字符串作为替换字符串。

Or use the zip() answer, which is also fine. 或者使用zip()答案,这也没关系。

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

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