繁体   English   中英

如何用列表值顺序替换文本文件中的字符串?

[英]How to replace strings in text file with list values in order?

我有一个文本文件,其中包含以下数据:

****File1*****
a     jhk
b     hfd
file  f1.txt     ;file open
hh       dsfsd        
----
qqw      adas
file    f2.txt     ;file open
hjh     dfd


****File2*****
d     sdfsd
b     sdfsd
file   f3.txt     ;file open
sada     dsfsd        
----
qqw     sdfsd
file    f4.txt     ;file open
wqeq     dfd

我有一个清单

    files=['a.txt','b.txt','c.txt','d.txt']

我想用列表中的值顺序替换文本文件中的字符串(文件)。 例如:我希望将文本文件中的“ f1.txt”替换为“ a.txt”,然后用“ b.txt”替换“ f2.txt” ...同样。

我试过的是:

fileName=input("Enter Input File Name: ")
f1=open(fileName,'r')
outFile=input("Enter Output File: ")
f2=open(outFile,'w')
nr=csv.reader((open("graphScript.csv")))
rn=0
b=[]
gFlag=0
global files
files=[]
for row1 in nr:
        b.append(row1)
        rn+=1
global nGraph
df=pd.read_csv("graphScript.csv")
files=list(df[df.columns[0]][4:])

for line in f1.readlines():
    word=line
    count = 0
    ----

    if re.search(r'/file',word):
        strplit=word.split()[1]
        for i in files:
            word=strplit.replace(strplit,i)
            f2.write(word)
    else:
           f2.write(word)

每当我运行此代码时,输​​出都会显示为:

    ****File1*****
    a     jhk
    b     hfd
    a.txtb.txtc.txtd.txt
    hh       dsfsd        
    ----
    qqw      adas
    a.txtb.txtc.txtd.txt
    hjh     dfd


    ****File2*****
    d     sdfsd
    b     sdfsd
    a.txtb.txtc.txtd.txt
    sada     dsfsd        
    ----
    qqw     sdfsd
    a.txtb.txtc.txtd.txt
    wqeq     dfd

我实际上想要的输出是:

****File1*****
a     jhk
b     hfd
file  a.txt     ;file open
hh       dsfsd        
----
qqw      adas
file    b.txt     ;file open
hjh     dfd


****File2*****
d     sdfsd
b     sdfsd
file   c.txt     ;file open
sada     dsfsd        
----
qqw     sdfsd
file    d.txt     ;file open
wqeq     dfd

如何解决呢?

一次使用re.sub替换一次。

f1=f1.read()
for i in files:
    f1=re.sub('f\d.txt',i,f1,1)
print(f1,file=f2)

暂无
暂无

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

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