首页 > 解决方案 > 替换文件中文本的有效方法

问题描述

我有一堆大文本文件(每个文件超过 500 万行)。如果它包含列表中的任何关键字(6000 个关键字),我必须在该行中添加一个前缀。

这是我写的代码:

import os

mypath = "D:\\Temp"
files = os.listdir(mypath)

fcounter = 0

for file in files:

    fl = open(mypath + file, 'r')
    lines = fl.readlines() 
    fl.close
    
    fl2 = open("D:\\Temp\\Keys.txt", 'r')
    keys = fl2.readlines()
    
    for i, line in enumerate(lines):
        if i % 100000 == 0:
            print(i)
        for key in keys:
            if line.find(key.strip()) > 3:
                lines[i] = '$' + line
                print(line)
    
    fl = open(mypath + file, 'w')
    
    for line in lines:
        fl.write("".join(line))

    fl.close()
    fl2.close()
    fcounter += 1
    print(f'Processed {fcounter}')

这是非常缓慢的。在我的系统上处理一个文本文件需要几个小时。有没有更好的方法来做到这一点?

标签: python

解决方案


推荐阅读