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

标签 python

我正在尝试编写一个程序,将文件中的所有字母交换为不同的字母。 当我使用超过 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'

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

关于python - 替换文件中所有选定的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17527188/

相关文章:

python - 自己写魔术方法可以吗?

python - 如何通过 http 和 https 为 conda/anaconda 配置代理?

python - 将列表中的随机值分配给变量时出现TypeError?

python - 如何包含外部 Python 代码以在其他文件中使用?

python - 如何从EXE中提取32x32图标位图数据并将其转换为PIL Image对象?

python - 段错误捕获

python - 更新应用引擎实体

python - Python 中的空返回是什么意思?

python - 转储文件中的多个对象

python - 如何评估 Sympy Optics 模块的 TWave 实例?