我想使用文本文件中的编码指令替换字符.
我的文本文件包含以下行:
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)
这是一个简单的要点,您可以查看并获得一些帮助
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)
| 归档时间: |
|
| 查看次数: |
29061 次 |
| 最近记录: |