gpt4 book ai didi

python无需逐行替换文本文件中的单词

转载 作者:太空宇宙 更新时间:2023-11-04 10:39:44 28 4
gpt4 key购买 nike

我有一个文本文件,比如:

This is a text document
written in notepad

我想用"file"一词替换“文档”,用“记事本”一词替换“记事本”,然后我想保存/覆盖文件。现在,无需逐行进行,因为我知道我可以做到

wordReplacements = {'document':'file', 'notepad':'Notepad'}
contents = open(filePath, 'r')
for line in contents:
for key, value in wordReplacements.iteritems():
line = line.replace(key, value)
contents.close()

但是有没有办法不用一行一行地做呢?注意:我使用的是 python 2.7。

最佳答案

引自docs ,

For reading lines from a file, you can loop over the file object. This is memory efficient, fast, and leads to simple code

如果我是你,我会这样做

import os
wordReplacements = {'document':'file', 'notepad':'Notepad'}

def transform_line(line):
for key, value in wordReplacements.iteritems():
line = line.replace(key, value)
return line

with open("Output.txt", "w") as output_file, open("Input.txt") as input_file:
for line in input_file:
output_file.write(transform_line(line))

os.rename("Output.txt", "Input.txt")

如果你更喜欢单行代码,你可以用这个替换 with 部分

with open("Output.txt", "w") as output_file, open("Input.txt") as input_file:
output_file.write("".join(transform_line(line) for line in input_file))

如果内存不是问题,而你又不想遍历文件对象,你可以将整个文件的内容移动到内存,然后在那里替换它

import re
with open("Input.txt") as open_file:
data = open_file.read()
for key, value in wordReplacements.iteritems():
data = re.sub(key, value, data)
with open("Input.txt", "wb") as open_file:
open_file.write(data)

关于python无需逐行替换文本文件中的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21370948/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com