Skip to main content
 首页 » 编程设计

python之替换文件中所有选定的字符

2025年05月04日15kevingrace

我正在尝试编写一个程序,将文件中的所有字母交换为不同的字母。 当我使用超过 line.replace 时,它​​会写入两倍的文本。 需要有效的方法将每个字符变成不同的字符。 任何想法表示赞赏。

import sys,os,time 
f1 = open('test.txt', 'r') 
f2 = open("test.encrypted", 'w') 
for line in f1: 
      f2.write(line.replace('a', '~'))  <--- Need more character lists to replace 
      f2.write(line.replace('b', '~')) 
 
f1.close() 
f2.close() 
print(f1) 

请您参考如下方法:

您可以使用 translate 同时执行所有替换内置于字符串中的方法。 string.maketrans()函数有两个参数,第一个是一个字符串,列出要替换的字符,第二个字符串(必须与第一个长度相同)显示第一个字符串中相应位置的替换字符。

>>> import string 
>>> t = string.maketrans('abcdefghijklmnopqrstuvwxyz', 'zyxwvutsrqponmlkjihgfedcba') 
>>> s = 'this is a string that will get mixed up' 
>>> s.translate(t) 
'gsrh rh z hgirmt gszg droo tvg nrcvw fk' 

...然后写出完成的字符串。