【问题标题】:Find and replace texts in all files from the text file input using Python in Notepad++在 Notepad++ 中使用 Python 从文本文件输入中查找和替换所有文件中的文本
【发布时间】:2017-02-06 21:26:32
【问题描述】:

我正在使用 Notepad ++ 执行查找和替换功能。目前我有大量的文本文件。我需要替换不同文件中的不同字符串。我想分批做。例如。

我有一个包含大量文本文件的文件夹。我有另一个文本文件,其中包含按顺序查找和替换的字符串

Text1 Text1-更正

Text2 Text2 更正

我有一个小脚本,仅对 Notepad++ 中打开的文件执行此替换。为了实现这一点,我在 Notepad++ 中使用了 python 脚本。代码如下。

 with open('C:/replace.txt') as f:
 for l in f:
    s = l.split()
    editor.replace(s[0], s[1]) 

简单来说,查找和替换函数应该从文件中获取输入。

提前致谢。

【问题讨论】:

    标签: python replace find notepad++


    【解决方案1】:
    with open('replace.txt') as f:
        replacements = [tuple(line.split()) for line in f]
    for filename in filenames:
        with open(filename, 'w') as f:
            contents = f.read()
            for old, new in replacements:
                contents = contents.replace(old, new)
            f.write(contents)
    

    将替换读入元组列表,然后遍历每个文件,将内容读入内存,进行替换,然后将其写回。我认为这些文件会被正确覆盖,但您可能需要仔细检查。

    【讨论】:

    • 感谢帕特里克的回复。在哪里设置源文件夹路径?代码中没有提到。请帮助我。
    • python 脚本“在”你运行它的任何地方。要更改它所在的目录,请使用 os 模块中的 chdir 函数:docs.python.org/3/library/os.html#process-parameters
    • 代码不工作。我已经设置了工作文件夹并尝试了代码。它不起作用。它显示的错误代码是 `for filename in filenames: NameError: name 'filenames' is not defined`
    • @PradeepAugustine 创建一个列表filenames,其中包含您要修改的文件的名称。
    • 我希望修改其根目录及其子文件夹中的所有文件。我使用的Final代码是import os os.chdir('c:\\Users\Prade\Desktop\Bible Format\Bible') with open('replace.txt') as f: replacements = [tuple(line.split()) for line in f] for filename in files: with open(filename, 'w') as f: contents = f.read() for old, new in replacements: contents = contents.replace(old, new) f.write(contents)同样的错误。
    猜你喜欢
    • 2011-06-12
    • 2018-02-04
    • 2019-07-30
    • 2017-03-24
    • 2013-05-27
    • 1970-01-01
    • 2020-07-29
    • 1970-01-01
    • 2012-02-14
    相关资源
    最近更新 更多