考虑匹配和顺序合并 2 个字符串的字符 python

combine characters of 2 strings considering match and order python

我有一个像这样的文件:

s
q
s
s
e

和文件 B:

*************m******************************m**m******************m********m

我必须根据文件 A 的列表替换文件 B 中的 "m",例如:

*************s******************************q**s******************s********e

我做了一些但不起作用:

    filea = open("filea.txt")
fileb = [line.rstrip('\n') for line in open("fileb.txt")]
for tc in filea:
    dew = fileb[0]
    pus = -1
    while True:
        pus = dew.find('m', pus + 1)
        if pus == -1:
            dew.replace('m', tc)

这是一个有效的方法,它只是一个快速的解决方案。

with open("filea.txt", "r+") as write_file:
    line = write_file.readline()
    read_file = open("fileb.txt", "r")
    line2 = read_file.readlines()
    read_file.close()
    for ch in line2:
        ch = ch.replace('\n', '')
        line = line.replace('m', ch, 1)
write_file.seek(0)
write_file.write(line)

这是解决方案。

file_a = './filea.txt'
file_b = './fileb.txt'

with open(file_a, 'r') as f:
    list_a = [str(x).strip() for x in f.readlines()]

with open(file_b, 'r') as f:
    str_b = f.readline()

for c in list_a:
    str_b = str_b.replace("m", c, 1)

# print(str_b)

replace (before, after) 将所有 before 字符串替换为 after 它。
你应该使用 replace(before, after, times)。您可以使用 times.

指定替换次数

tc包含\n,所以需要tc.strip()

您可以将 iternext 结合使用,并结合 re.sub:

import re
vals = (i.strip('\n') for i in open('fileA.txt'))
result = re.sub('\w+', lambda _:next(vals), open('fileB.txt').read())
with open('fileB.txt', 'w') as f:
  f.write(result)

fileB.txt 的内容:

*************s******************************q**s******************s********e'