【问题标题】:What is an easy to adapt alternative to multidict for Python 2?什么是 Python 2 的 multidict 易于适应的替代方案?
【发布时间】:2020-02-24 19:00:28
【问题描述】:

标题说明了一切。

我正在尝试从不支持 Python 3 的 virtualenv 和 as multidict doesn't support Python 2 运行对 this code 的改编,我想在考虑更改之前考虑可以与 Python 2 一起使用的此模块的替代方案我的主人。

使用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

提前致谢!

【问题讨论】:

  • 没错,@Carcigenicate。这是一个我忽略的好方法,以便找到某种适当的方法来使用类似的模块来做到这一点,但如果我找不到它,那就必须是这种情况。
  • tmpDict 是一个常规字典(因此键形成一个集合),这意味着 fullTermsDict 也可以是常规字典;您永远不会尝试向其添加相同的密钥两次。实际上,您只需要一个 collections.Counter 的实例。

标签: python python-2.7 module


【解决方案1】:

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

# 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_case,而不是camelCase。

【讨论】:

  • 再一次好点。在修改它的同时,我正在使这段代码适应我的最终约定,但我仍在学习,所以我对发送拉取请求感到不舒服,例如。无论如何,非常感谢你为这个话题带来的启发!
【解决方案2】:

您不需要成熟的多语种;你只需要一个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)

【讨论】:

    猜你喜欢
    • 2023-01-19
    • 2016-04-04
    • 2015-12-25
    • 2011-04-07
    • 1970-01-01
    • 2021-11-13
    • 2018-12-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多