python - 替换文件中文本的有效方法
问题描述
我有一堆大文本文件(每个文件超过 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}')
这是非常缓慢的。在我的系统上处理一个文本文件需要几个小时。有没有更好的方法来做到这一点?
解决方案
推荐阅读
- jwt - 创建基于ip地址的JWT认证
- java - 如何正确连接 SQLite 与 JavaFX 中的文本字段和标签?
- c++ - 类中未声明的字符串标识符
- mysql - Laravel:加入多个选择语句
- puppet - Puppet、Puppet Master 和 Puppet Server 的区别
- xamarin - 有没有办法在 Xamarin.Forms 中实现 Stripe 卡小部件?
- python - Tweepy 转推机器人不断循环
- java - 如何解决会话超时问题?
- php - 如何使用同一服务器访问不同codeigniter项目中的同一会话?
- r - 在带有 purrr 的大型列表列表中对不同位置和不同名称的列进行子集