如何在这段代码中优化整体处理时间?

2024-04-27 03:39:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经写了一个代码,将一组文档作为一个列表,并将另一组单词作为一个列表,然后如果在每个文档中检查是否有任何单词包含在单词列表中,我就用可用的单词造句

//find whether the whole word in the sentence- return None if its not in.
def findWholeWord(w):
  return re.compile(r'\b({0})\b'.format(w), flags=re.IGNORECASE).search



for data in dataset['abc']:
  mvc = ''
  for x in newdataset['Words']:
    y = findWholeWord(x)(data)
    if y != None:
      mvc = mvc+" "+ x

  document.append(mvc)      

当我用平均字数为10的10000个文档运行这段代码时,会花费很长时间。如何优化此代码?或者此代码的可能替代项来实现相同的功能


Tags: the代码in文档renone列表for
2条回答

你确定这些代码运行缓慢吗?我不是。我想你大部分时间都在打开文件。你需要像威尔说的那样分析你的代码。您还可以使用multiprocessing来提高代码的速度。你知道吗

因为您只想检查单词是否存在于abc集合中,所以不需要使用re。你知道吗

for raw_data in dataset['abc']:
  data = raw_data.lower()
  mvc = ''
  for x in newdataset['Words']:
    if x not in data:
      mvc = mvc+" "+ x

  document.append(mvc)  

相关问题 更多 >