我在寻找单词列表中所有单词在对话中被找到的次数。不考虑每个单词的单个频率,而只考虑总数。单词表包括ngrams upill 3
from nltk.util import ngrams
find = ['car', 'motor cycle', 'heavy traffic vehicle']
data = pd.read_csv('inputdata.csv')
def count_words(doc, find):
onegram = [' '.join(grams) for grams in ngrams(doc.split(), 1)]
bigrams = [' '.join(grams) for grams in ngrams(doc.split(), 2)]
trigrams = [' '.join(grams) for grams in ngrams(doc.split(), 3)]
n_gram = onegrams + bigrams + trigrams
''' get count of unique bag of words present in doc '''
lst = ".".join([i for i in find if i in n_gram])
cnt = np.count_nonzero(np.unique(lst.split(".")))
return cnt
result = data['text'].apply(lambda x: count_words(x, find))
这些步骤的处理量非常大,在数据集较大的情况下运行需要很长时间。优化现有方法的选择是什么?或者是否有其他替代步骤?在
首先,将doc拆分一次,而不是每次调用三次。在
其次,使用collectionsCounter类可以很好地进行计数。那么,计数在代码中是微不足道的,而且是Python所能达到的最快速度。在
相关问题 更多 >
编程相关推荐