【发布时间】:2020-03-14 10:53:06
【问题描述】:
我有一个问题已解决,但没有以有效的方式解决。我有一个字符串列表,它们是图像的标题。我需要获取此字符串列表中的任何单词并创建一个包含以下信息的字典
- 单词,如果该单词在该列表中出现 5 次或更多次
- 该词的简单 id
因此,我在 python 字典中的词汇表将包含 word:id 条目
首先,我有一个辅助函数可以将字符串划分为标记或单词
def split_sentence(sentence):
return list(filter(lambda x: len(x) > 0, re.split('\W+', sentence.lower())))
然后,我将生成这样的词汇表,这很有效
def generate_vocabulary(train_captions):
"""
Return {token: index} for all train tokens (words) that occur 5 times or more,
`index` should be from 0 to N, where N is a number of unique tokens in the resulting dictionary.
"""
#convert the list of whole captions to one string
string=listToStr = ' '.join([str(elem) for elem in train_captions])
#divide the string tokens (individual words), by calling the previous function
individual_words=split_sentence(string)
#create a list of words that happen 5 times or more in that string
more_than_5=list(set([x for x in individual_words if individual_words.count(x) >= 5]))
#generate ids
ids=[i for i in range(0,len(more_than_5))]
#generate the vocabulary(dictionary)
vocab = dict(zip(more_than_5,ids))
return {token: index for index, token in enumerate(sorted(vocab))}
对于相对较小的标题列表,该代码就像一个魅力。但是,对于具有数千个长度的列表(例如,80000),它会永远持续下去。我现在正在运行此代码一小时。
有什么方法可以加快我的代码速度?如何更快地计算 more_than_5 变量?
编辑:我忘了提到,在这个字符串列表的极少数特定成员中,在句子开头的某些元素中有 \n 符号。是否可以从我的列表中删除这个符号,然后再次应用算法?
【问题讨论】:
标签: python python-3.x python-2.7