用Python替换字符串
我有一个链接列表:
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')
但是我还有很多行需要处理,这让我花了很多时间 :( 请告诉我怎么替换这些行。谢谢!
2 个回答
1
我猜当你运行 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') )
2
用正则表达式替换字符串的一部分
看看下面的解决方案:
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_content = open('fileinput','r').read()
然后再对 file_content
变量进行操作,这个变量是字符串,包含了你读取的整个文件内容。