【发布时间】:2019-09-14 12:47:18
【问题描述】:
我写了一段代码,基本上是从文本文件的列表中执行查找和替换。
因此,它将整个列表映射到字典中。然后从文本文件中处理每一行,并与字典中的整个列表匹配,如果在该行中的任何位置找到匹配项,它将替换为列表(字典)中的相应值。
代码如下:
import sys
import re
#open file using open file mode
fp1 = open(sys.argv[1]) # Open file on read mode
lines = fp1.read().split("\n") # Create a list containing all lines
fp1.close() # Close file
fp2 = open(sys.argv[2]) # Open file on read mode
words = fp2.read().split("\n") # Create a list containing all lines
fp2.close() # Close file
word_hash = {}
for word in words:
#print(word)
if(word != ""):
tsl = word.split("\t")
word_hash[tsl[0]] = tsl[1]
#print(word_hash)
keys = word_hash.keys()
#skeys = sorted(keys, key=lambda x:x.split(" "),reverse=True)
#print(keys)
#print (skeys)
for line in lines:
if(line != ""):
for key in keys:
#my_regex = key + r"\b"
my_regex = r"([\"\( ])" + key + r"([ ,\.!\"।)])"
#print(my_regex)
if((re.search(my_regex, line, re.IGNORECASE|re.UNICODE))):
line = re.sub(my_regex, r"\1" + word_hash[key]+r"\2",line,flags=re.IGNORECASE|re.UNICODE|re.MULTILINE)
#print("iam :1",line)
if((re.search(key + r"$", line, re.IGNORECASE|re.UNICODE))):
line = re.sub(key+r"$", word_hash[key],line,flags=re.IGNORECASE|re.UNICODE|re.MULTILINE)
#print("iam :2",line)
if((re.search(r"^" + key, line, re.IGNORECASE|re.UNICODE))):
#print(line)
line = re.sub(r"^" + key, word_hash[key],line,flags=re.IGNORECASE|re.UNICODE|re.MULTILINE)
#print("iam :",line)
print(line)
else:
print(line)
这里的问题是当列表大小增加时,执行速度会变慢,因为文本文件的所有行都与列表中的每个键匹配。那么我在哪里可以改进这段代码的执行呢。
列表文件:
word1===>替换word1
word2===>替换word2
.....
列表是制表符分隔的。为了便于理解,这里我使用了 ===>。
输入文件:
hello word1 I am here.
word2. how are you word1?
预期输出:
hello replaceword1 I am here.
replaceword2. how are you replaceword1?
【问题讨论】:
-
您能发布示例输入文件和预期输出吗?
-
添加样本输入输出@Rakesh
-
我有很多输入文件,每个文件在 100 到 200 行之间,从 8K 到 20 K
-
将整个文本读入内存,替换单词并保存回来应该是最简单的!在@Nagaraju 下方查看我的答案
标签: regex python-3.x performance dictionary