对于Python2来说,什么是multidict的一个易于调整的替代方案?

2024-04-27 22:44:44 发布

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

标题说明了一切

我试图从不支持Python 3和{a2}的VielalEnv中运行一个对{A1}的自适应,我想考虑这个模块的替代品,它可以在考虑更改主机之前使用Python 2。p>

使用multidict功能的代码的关键部分如下:

def getFrequencyDictForText(sentence):
    fullTermsDict = multidict.MultiDict()
    tmpDict = {}

    # making dict for counting frequencies
    for text in sentence.split(" "):
        if re.match("a|the|an|the|to|in|for|of|or|by|with|is|on|that|be", text):
            continue
        val = tmpDict.get(text, 0)
        tmpDict[text.lower()] = val + 1
    for key in tmpDict:
        fullTermsDict.add(key, tmpDict[key])
    return fullTermsDict

提前谢谢


Tags: 模块thekeytextina2标题for
2条回答

我认为可以使用带有默认列表值的^{}来获得近似值:

# Each new value is created by calling the "list" function
# Saves you from needing to do a "if key not in fullTermsDict" check prior to "append"ing
fullTermsDict = defaultdict(list)  

. . .

fullTermsDict[key].append(tmpDict[key])

必须注意:Python更喜欢snake_大小写,而不是camelCase

你不需要一个完整的多目录;你只需要一个Counter

from collections import Counter

def get_frequency_dict_for_text(sentence):
    skip_words = {"a", "the", "an", ...}

    words = (x.lower() for x in sentence.split(" ") if x not in skip_words)
    return Counter(words)

相关问题 更多 >