用 Python 替换文件中的文本 [英] replacing text in a file with Python

查看:54
本文介绍了用 Python 替换文件中的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Python 新手.我希望能够打开一个文件并通过 Python 用给定的替换替换某些单词的每个实例.例如,将每个单词零"替换为0",将临时"替换为bob",将垃圾"替换为无".

我第一次开始使用这个:

 for line in fileinput.input(fin):fout.write(line.replace('零', '0'))fout.write(line.replace('temp','bob'))fout.write(line.replace('垃圾','没什么'))

但我不认为这是一个甚至远程正确的方法来做到这一点.然后我考虑执行 if 语句来检查该行是否包含这些项目,如果包含,则替换该行包含的项目,但根据我对 Python 的了解,这也不是真正的理想解决方案.我很想知道这样做的最佳方法是什么.提前致谢!

解决方案

应该这样做

replacements = {'zero':'0', 'temp':'bob', 'garbage':'nothing'}使用 open('path/to/input/file') 作为 infile,open('path/to/output/file', 'w') 作为 outfile:对于 infile 中的行:对于 src,replaces.items() 中的目标:line = line.replace(src, target)outfile.write(行)

编辑:解决Eildosa 的评论,如果您想在不写入另一个文件的情况下执行此操作,那么您最终将不得不将整个源文件读入内存:

lines = []使用 open('path/to/input/file') 作为 infile:对于 infile 中的行:对于 src,replaces.items() 中的目标:line = line.replace(src, target)行.追加(行)使用 open('path/to/input/file', 'w') 作为输出文件:对于线中线:outfile.write(行)

如果您使用的是 Python 2.x,请使用 replacements.iteritems() 而不是 replacements.items()>

I'm new to Python. I want to be able to open a file and replace every instance of certain words with a given replacement via Python. as an example say replace every word 'zero' with '0', 'temp' with 'bob', and say 'garbage' with 'nothing'.

I had first started to use this:

for line in fileinput.input(fin):
        fout.write(line.replace('zero', '0'))
        fout.write(line.replace('temp','bob'))
        fout.write(line.replace('garbage','nothing'))

but I don't think this is an even remotely correct way to do this. I then thought about doing if statements to check if the line contains these items and if it does, then replace which one the line contains, but from what I know of Python this also isn't truly an ideal solution. I would love to know what the best way to do this. Thanks ahead of time!

解决方案

This should do it

replacements = {'zero':'0', 'temp':'bob', 'garbage':'nothing'}

with open('path/to/input/file') as infile, open('path/to/output/file', 'w') as outfile:
    for line in infile:
        for src, target in replacements.items():
            line = line.replace(src, target)
        outfile.write(line)

EDIT: To address Eildosa's comment, if you wanted to do this without writing to another file, then you'll end up having to read your entire source file into memory:

lines = []
with open('path/to/input/file') as infile:
    for line in infile:
        for src, target in replacements.items():
            line = line.replace(src, target)
        lines.append(line)
with open('path/to/input/file', 'w') as outfile:
    for line in lines:
        outfile.write(line)

Edit: If you are using Python 2.x, use replacements.iteritems() instead of replacements.items()

这篇关于用 Python 替换文件中的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆