if info_list[key] in content:
if content.find(info_list[key]) != -1
这两个查找字符串的效率差异。
bb.txt
5G 的文件,前者跑了 8 小时,find
跑了 20 小时。
汗!! 有没有更快捷的方法?
#coding:utf-8
import os
import sys
def getList(filename) :
fp = open(filename, 'r')
info_list = {}
for line in open(filename):
line = fp.readline()
tmp = line.strip('\n').split('\t')
info_list[tmp[0]] = tmp[1]
fp.close()
return info_list
def matchname(info_list, input_file, output_file) :
fp = open(input_file, 'r')
fw = open(output_file, 'a')
for line in open(input_file):
line = fp.readline()
tmp = line.strip('\n').split('\t')
content = tmp[2]
for key in info_list:
if info_list[key] in content:
#if content.find(info_list[key]) != -1 :
result = tmp[0] + '\t' + tmp[1] + '\t' + info_list[key] + '\t' + key + '\n'
fw.write(result)
else :
continue
fw.close()
fp.close()
if __name__ == '__main__':
# date=sys.argv[1]
info_filename = 'aa.txt'
content_filename = 'bb.txt'
result_filename = 'final_output2.txt'
info_list = getList(info_filename)
matchname(info_list, content_filename, result_filename)
print('done...')
a@bj-m-20a:~/study/python_learn$ cat aa.txt
aaa 赵六
bbb 赵四
ccc 李丽
ddd 吴小龙
a@bj-m-20a:~/study/python_learn$ cat bb.txt
001 0001 李丽你好啊李丽是个大美女
002 0002 赵四家的后厨赵六你是我的爱
003 0003 吴小龙上次数学考的不及格
a@bj-m-20a:~/study/python_learn$ cat final_output2.txt
001 0001 李丽 ccc
001 0001 李丽 ccc
002 0002 赵六 aaa
002 0002 赵四 bbb
003 0003 吴小龙 ddd
001 0001 李丽 ccc
002 0002 赵六 aaa
002 0002 赵四 bbb
003 0003 吴小龙 ddd
改了一下你的代碼, 這樣應該比較簡潔:
(根據 @依云 的建議又改了一下)
(稍後回來補說明...)
我回答過的問題: Python-QA