替换文件中的字符

nrj*_*nrj 8 python

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

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

This is a message
Run Code Online (Sandbox Code Playgroud)

我想更换a -> e,e -> a,s -> 3

所以该行写道:

Thi3 i3 e massega
Run Code Online (Sandbox Code Playgroud)

我尝试了以下代码,但它一次只更改了一行中的一个字符.

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()
Run Code Online (Sandbox Code Playgroud)

rob*_*ert 11

替换这个:

newcontents = contents.replace('a','e')
newcontents = contents.replace('s', '3')
Run Code Online (Sandbox Code Playgroud)

有了这个:

newcontents = contents.replace('a','e')
newcontents = newcontents.replace('s', '3')
Run Code Online (Sandbox Code Playgroud)

或者更好的是:

newcontents = contents.replace('a','e').replace('s', '3')
Run Code Online (Sandbox Code Playgroud)

您的代码似乎只会尝试将'a'替换为'e',而不是'e'替换为'a'.为此,您需要以下内容:

import string
newcontents = contents.translate(string.maketrans("aes", "ea3"))
Run Code Online (Sandbox Code Playgroud)

  • 请注意,OP似乎想要替换`a - > e`和`e - > a`,这只有在并行完成时才能工作,因为替换的顺序执行将导致`tea` - (`a - > e`) - >`tee` - (`e - > a`) - >`taa`,这可能不是,OP希望拥有什么.所以替换是错误的方法. (4认同)
  • +1为[**`str.translate()`**](http://docs.python.org/library/stdtypes.html#str.translate).这是要走的路! (4认同)

Sid*_*cks 6

这是一个简单的要点,您可以查看并获得一些帮助

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
Run Code Online (Sandbox Code Playgroud)