【问题标题】:How to replace strings in text file with list values in order?如何按顺序用列表值替换文本文件中的字符串?
【发布时间】:2019-10-18 14:59:23
【问题描述】:

我有一个包含以下数据的文本文件:

****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”,然后将“f2.txt”替换为“b.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

如何解决这个问题?

【问题讨论】:

    标签: python python-3.x string list replace


    【解决方案1】:

    一次替换使用re.sub

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

    【讨论】:

    • 你得到了什么
    猜你喜欢
    • 1970-01-01
    • 2019-05-16
    • 1970-01-01
    • 2016-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多