[英]Python: words replacing in huge text
我有一个巨大的文本和一个大约 10K 的单词列表。 Python 中用其他单词替换所有这些单词的最快方法是什么?
编辑:文本大小> 1Gb,文本是人工编写的,并且“非常标记化”(任何字母数字字符和任何其他单个符号的运行都被拆分为新标记)
多个单词> 10K,文本中的每个词频为1,替换词在所有替换中都相同。 Python 2.5-2.7
如果接近开始,输入格式和搜索/替换配对信息将需要完善这个答案,但这将是我最初的尝试(假设输入数据中存在某种形式的规律性,在我的示例代码中用空格分隔以下)。
replacements = {
's1': 'r1',
's2': 'r2'
...
}
with open('input.txt') as fhi, open('output.txt', 'w') as fho:
for line in fhi:
words = line.split(' ')
fho.write(' '.join(map(lambda w: replacements.get(w, w), words))
# Or as a list comprehension from the comments.
fho.write(' '.join([replacements.get(w, w) for w in words]))
这里的想法是,我们将从输入文件将数据重定位到 output 文件中。 对于每一行的每个单词,我们检查它是否在我们的替换字典中。 如果是,我们检索新值,否则通过dict.get(key[, default])
方法返回未更改的单词。 这可能并不理想,不处理标点符号,可能会在输入文件没有分成几行时遇到问题等,但可能是一种入门方式。
哇。 这一点都不是微不足道的:这是一个想法:
Step 1: Quantize the text into words, signs etc. The function quantize accepts text as an argument, the output is the list of words and signs. def quantize(text: str) -> list: ... An inverse function that can construct the a from a given list: def dequantize(lst: list) -> str: .... Step 2: Build a dictionary of quantized list, so that d_rep[word] = word Then, use the replacements word lists to transform this dictionary as follows: d_rep[word] = replacement Step 3: Go through every word in quantized list and replace it with a value from d_rep dictionary. It might be the original word or a replacement. Step 4: Dequantize the list and restore the text.
如果您有大文本和大量搜索/替换词,这应该是最佳选择。 祝你好运,问。 如果您有任何实施问题。
更新:使用单个替换词,它更容易,从“10K”词表创建一个集合,然后对于量化列表中的每个单词,如果单词在集合中,则在该列表中替换它。
在伪 python 代码中:
qlist = quantize(text)
for i in range(0, len(qlist)):
word = qlist[i]
if word in wordlist_set:
qlist[i] = 'replacement'
text = dequantize(qlist)
如果您有足够的 memory,最快的方法可能是将文本读取为字符串并使用正则表达式搜索并执行替换:
def replace(matched):
# Matched.group(0) is the word that was found
# Return the replacement
return "REPLACEMENT"
# The \b ensure that only whole words are matched.
text = re.sub(r"\b(%s)\b" % "|".join(words), replace, text)
如果您没有 memory,请尝试分块进行,也许:
# Read a chunk and a line to ensure that you're not truncating a word.
chunk = text_file.read(1024 ** 2) + text_file.readline()
我建议一种简单的方法,一次替换一行:
pattern1 = 'foo'
pattern2 = 'bar'
with open('input.txt') as input, open('output.txt', 'w') as output:
for line in input:
output.write(line.replace(pattern1, pattern2))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.