Python单行代码用文本文件中的另一个单词替换一个单词

prr*_*rao 2 python

我正在尝试使用Python(通过Linux终端)替换文本文件的以下行中的"example"一词text_file.txt:

abcdefgh example uvwxyz
Run Code Online (Sandbox Code Playgroud)

我想要的是:

abcdefgh replaced_example uvwxyz
Run Code Online (Sandbox Code Playgroud)

我可以用Python中的单线程做到这一点吗?

编辑: 我有一个perl单行,perl -p -i -e 's#example#replaced_example#' text_file.txt但我也想用Python做

mgi*_*son 9

你能行的:

python -c 'print open("text_file.txt").read().replace("example","replaced_example")'
Run Code Online (Sandbox Code Playgroud)

但它相当笨重.Python的语法并不是为了制作漂亮的1-liners而设计的(虽然经常以这种方式运行).Python重视其他所有内容的清晰度,这是您需要导入内容以获得python必须提供的真正强大工具的一个原因.由于你需要导入东西才能真正利用python的强大功能,因此它无法从命令行创建简单的脚本.

我宁愿使用专为此类设计的工具 - 例如sed:

sed -e 's/example/replace_example/g' text_file.txt
Run Code Online (Sandbox Code Playgroud)