Python根据字典替换字符串速度为什么超级慢-附代码

NA_QUEEN 2018-05-18 09:36:42
小白写了一个简单的代码,但运行起来速度很慢,不知道什么原因,请各位大侠指点

需求:从文本文件a.txt中找到包含B_dic的key的行,并在文本a.txt中将key替换成对应的value,写到out.txt中。
示例:b_dict:中国 China
a,txt: 我爱中国。---》out.txt:我爱China.

代码:
#!/usr/bin/python
# encoding: utf-8
# -*- coding: UTF-8 -*-
import re

def load_dict_from_file(filepath):
_dict = {}
try:
with open(filepath,'r') as dict_file:
for line in dict_file:
(key,value) = line.strip().split('\t')
_dict[key] = value
except IOError as ioerr:
print "file %s not existed" % (filepath)

return _dict

if __name__ == '__main__':
_dict = load_dict_from_file('slot_v4_20180509.txt') #从slot文件中生成字典格式

input_file = file('a.txt','r') #原始数据
lines = input_file.readlines()

output_file = file('out.txt','w') #替换为value
for line in lines:
for key in _dict:
line = line.replace(key,_dict[key]) #替换为value
output_file.write(line)
...全文
1269 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
NA_QUEEN 2018-05-23
  • 打赏
  • 举报
回复
引用 2楼oyljerry 的回复:
多在一些位置加上日志等,看看时间主要消耗在哪,很可能是文件读写比较费时间
嗯嗯 好的 多谢指点
NA_QUEEN 2018-05-18
  • 打赏
  • 举报
回复
一个小时才处理了三万行。。。。
oyljerry 2018-05-18
  • 打赏
  • 举报
回复
多在一些位置加上日志等,看看时间主要消耗在哪,很可能是文件读写比较费时间

37,718

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • IT.BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧