Replace String by python



i have list

http://lincoln.com/picture/2453345/flower.jpg
http://lincoln.com/picture/2354345/flower1.jpg

替换为:

http://lincoln.com/picture/4453345/flower.jpg
http://lincoln.com/picture/4354345/flower1.jpg

我试着:

f=open('fileinput','r')
f.replace('2453345/flower.jpg','4453345/flower.jpg')

但是我有更多的线。我做这件事花了很多时间。请告诉我如何更换线路。由于

使用正则表达式替换部分字符串

参见以下解决方案:

import re
regexp_test = re.compile('/d')
result = regexp_test.sub(lambda x: '/'+str(int(x.group()[1])+2), file_content)

它将斜杠("/")之后的每个数字增加2 ,因此"/2"将被"/4"取代,以此类推…

结果会给你:

>>> print result
http://lincoln.com/picture/4453345/flower.jpg
http://lincoln.com/picture/4354345/flower1.jpg

如果file_content定义如下:

>>> file_content = '''http://lincoln.com/picture/2453345/flower.jpg
http://lincoln.com/picture/2354345/flower1.jpg'''

使用文件内容作为字符串

正如@jsalonen正确注意到的那样,您的脚本还有另一个问题:它直接使用file,因为它将是一个字符串。您应该首先读取其内容:

file_content = open('fileinput','r').read()

,然后处理file_content变量,它是字符串,包含您已读取的文件的全部内容。

我猜当你运行你的f.replace你得到AttributeError: 'file' object has no attribute 'replace'因为-好- replace是一个字符串方法,但f是一个文件对象。

替换的一种方法是首先将文件的整个内容读入字符串,然后运行该字符串并将修改后的字符串重写回文件:

f=open('fileinput', 'r')
data=f.read()
f.close()
f.open('fileoutput', 'w')
f.write( data.replace('2453345/flower.jpg','4453345/flower.jpg') )
f.close()

如果您想逐行执行替换,只需使用split将数据分成几行并遍历它:

for line in data.split('n'):
   f.write( line.replace('xxx/flower.jpg', 'yyy/flower.jpg') )

最新更新