『壹』 python将指定文本中的字符串替换后,生成新的文本文件。

import os

os.chdir('d:\\') # 跳到D盘

if not os.path.exists('pp.txt'): # 看一下这个文件是否存在
exit(-1) #,不存在就退出

lines = open('pp.txt').readlines() #打开文件,读入每一行

fp = open('pp2.txt','w') #打开你要写得文件pp2.txt
for s in lines:
fp.write( s.replace('love','hate').replace('yes','no')) # replace是替换,write是写入
fp.close() # 关闭文件

『贰』 文本字符串替换python

withopen('xxx.txt','r')asfin:
withopen('yyy.txt','w')asfout:
forlineinfin:
line.replace('this','that')#replacethiswiththat
fout.write(line+' ')


『叁』 如何用Python来进行查询和替换一个文本字符串

1、说明
可以使用find或者index来查询字符串,可以使用replace函数来替换字符串。内
2、示例
1)查询
>>> 'abcdefg'.find('cde')
结果容为2
'abcdefg'.find('acde')
结果为-1
'abcdefg'.index('cde')
结果为2
2)替换
'abcdefg'.replace('abc','cde')
结果为'cdedefg'
3、函数说明
1)find(...)
S.find(sub[, start[, end]]) -> int
返回S中找到substring sub的最低索引,使得sub包含在S [start:end]中。 可选的 参数start和end解释为切片表示法。
失败时返回-1。
2)index(...)
S.index(sub[, start[, end]]) -> int
与find函数类似,但是当未找到子字符串时引发ValueError。
3)replace(...)
S.replace(old, new[, count]) -> str
返回S的所有出现的子串的副本旧换新。 如果可选参数计数为给定,只有第一个计数出现被替换。

『肆』 python 查找替换字符串

import re
f1=open('J:/wenjian/1/1.txt','r').read()#把整个来文自件读进来作为整个字符串
f1 = re.sub('abcdef','123456',f1)#替换所有符合的情况
f_w=open('J:/wenjian/1/replace_1.txt','wb')#新建一个文件,把替换后的内容写进去
f_w.write(f1)
f_w.close()

『伍』 python 查找字符串并将其替换

import re
f1=open('J:/wenjian/1/1.txt','r').read()#把整个文件读进来作为整个字符串
f1 = re.sub('abcdef','123456',f1)#替换所有符合的情况
f_w=open('J:/wenjian/1/replace_1.txt','wb')#新建一个文件,把替换后的内容写进去
f_w.write(f1)
f_w.close()

『陆』 python将指定文本中的字符串替换后,保存该文本文件。

txt=open("inputfile.txt","rb").readlines()
outputs=[]
for line in txt:
line=line.replace("/test","")
if line=="/X/ABC":
outputs.append(line)
outputs.append("/X/XYZ")
elif line=="/temp.txt":continue
else:outputs.append(line)
这样就行了吧。好象没有什么难度。如果要求在一行内完成,可能还是挺麻烦的。

『柒』 请问:使用python如何轻松实现替换多个文件中的字串

不太麻烦。先把文件读出来,然后如果没有正则匹配,可以考虑简单的
str.replace(a,
b)就可以了,然后再写回去即可。

『捌』 Python 根据字典的内容替换文本的里的字符串

我觉来得你好想想多了。自即然全文替换。哪么你只需要遍历你的dict

a_dict = {'apple':'1','tree':'2','123456':'3'}
input_file = open(r'd:\test_body.txt',"r").read();
for key,value in a_dict.items():
input_file=input_file.replace(key,value);

这样子不行吗?

『玖』 关于Python,怎样才能把字符串中某一个重复的字符都替换

#-*-coding:utf-8-*-
numbers='0123456789'
a="r1.5ml.in.9it"
file=[]
foriina:
file.append(i)
printfile

foridx,iinenumerate(file):
#先前来是因为第二次index('.')的时候,源获取的还是第一个点
ifi=='.'andi!=file[-1]andfile[idx+1]innumbers:
file[idx]='*'
else:
i=i
print(file)

如果解决了您的问题请点赞!
如果未解决请继续追问

『拾』 python 中字符串替换问题 指定字符串替换 比如 /test/a.txt 只替换 a 把a 变成b,c,d,e,f等等等怎么替换

python我也是刚接触,虽然很笨,不过可以实现,这个是正则方法
re.sub(r'/text/(\w).txt',r'/text/c.txt','/text/a.txt')
不过你这个完全可以采用字符串截断的方式进行实现.