Python 替换文件中的字符

Python 替换文件中的字符,python,Python,我想在文本文件中使用编码指令替换字符 我的文本文件包含以下行: This is a message 我想替换a->e,e->a,s->3 所以这句话是: Thi3 i3 e massega 我尝试了下面的代码,但它一次只更改行中的一个字符 import sys import codecs def encode(): path = "C:\Users\user\Desktop" basename = "assgn2part1.txt" filename = path + "\\"

我想在文本文件中使用编码指令替换字符

我的文本文件包含以下行:

This is a message
我想替换
a->e
e->a
s->3

所以这句话是:

Thi3 i3 e massega
我尝试了下面的代码,但它一次只更改行中的一个字符

import sys
import codecs

def encode():
  path = "C:\Users\user\Desktop"
  basename = "assgn2part1.txt"
  filename = path + "\\" + basename
  #file = open(filename, "rt")
  f = codecs.open(filename,encoding='utf-8')
  contents = f.read()


  print contents ,"\n"
  newcontents = contents.replace('a','e')
  newcontents = contents.replace('s', '3')

  print newcontents


  f.close()
替换此项:

newcontents = contents.replace('a','e')
newcontents = contents.replace('s', '3')
为此:

newcontents = contents.replace('a','e')
newcontents = newcontents.replace('s', '3')
或者更好:

newcontents = contents.replace('a','e').replace('s', '3')
您的代码似乎只尝试将“a”替换为“e”,而不是将“e”替换为“a”。为此,您需要以下几点:

import string
newcontents = contents.translate(string.maketrans("aes", "ea3"))
或者按照罗伯特的建议,使用字典

>>> strs="this is a message"
>>> dic={'a':'e','e':'a','s':'3'}
>>> strs="".join((dic.get(x,x) for x in strs))
>>> print(strs)
thi3 i3 e ma33ega
或:

>>> strs="this is a message"
>>> dic={'a':'e','e':'a','s':'3'}
>>> new_strs=''
>>> for x in strs:
     if x in dic:
        new_strs += dic[x]
     else:
        new_strs += x
>>> print(new_strs)

thi3 i3 e ma33ega
这里很好用

>>> import codecs
>>> contents = codecs.open('foo.txt', encoding='utf-8').read()
>>> print contents
This is a message.

>>> print contents.replace('s', '3')
Thi3 i3 a me33age.
注意:如果希望第二次替换正常工作,应在newcontents上执行:


您也可以使用regex

newcontents = re.sub(r"a","e",contents)
newcontents = re.sub(r"s","3",newcontents)

这里有一个简单的要点,你可以看到,并得到一些帮助

x = open("e:/a.txt" )
s=x.read().replace(''a", "xy" ) 
x.close()

//Now open the file in write mode and write the string with replaced

x=open("e:/a.txt","w")
x.write(s)
x.close

请注意,OP似乎希望替换
a->e
e->a
,这只有在并行执行时才能工作,因为顺序执行替换将导致
tea
a->e
)-->
tee
e->a
)-->
taa
,这可能不是OP想要的。因此,替换是错误的方法。这就是路!我想他们应该在没有内置函数的情况下实现这一点。@thg435:就像没有一样?@thg435:我看到了,但是OP确实使用了
str.replace()
。你应该使用它来正确地组合路径。我想预期的输出是:
thi3 i3 e ma33ega
?@AshwiniChaudhary:无需猜测。问题很明确。我不太喜欢这种方法,但至少用一个
dict
而不是一堆
if
/
else
条件。@robert suggestion implemed+1,我建议让最后一个对初学者来说更具可读性(即循环代替理解,if else代替get)1.这似乎与问题无关。OP的主要问题是如何替换,而不是IO。
newcontents = re.sub(r"a","e",contents)
newcontents = re.sub(r"s","3",newcontents)
x = open("e:/a.txt" )
s=x.read().replace(''a", "xy" ) 
x.close()

//Now open the file in write mode and write the string with replaced

x=open("e:/a.txt","w")
x.write(s)
x.close