【问题标题】:Creating a dictionary from a dictionary从字典创建字典
【发布时间】:2017-11-13 00:55:55
【问题描述】:

我正在尝试创建一种“dict of dicts”。第一级字典是词频键值对。由下面的 for 循环创建,'cleaned_words_string' 是包含我正在分析的文本的字符串,并且对于每个商店都是唯一的。

        stop_words = set(stopwords.words('english'))

        word_tokens = word_tokenize(cleaned_word_string)

        filtered_sentence = [w for w in word_tokens if not w in stop_words]

        filtered_sentence = []

        for w in word_tokens:
            if w.lower() not in stop_words:
                filtered_sentence.append(w)

        fw_freq = nltk.FreqDist(filtered_sentence).most_common()

        freq_dict = dict(fw_freq)

如何修改此代码以使每个单独的“商店名称”都附加到其 freq_dict?

类似:

Store_dict = {storename: freq_dict}

这样的输出将是:

Store_dict {'Target': freq_dict, 'WalMart':freq_dct 等}

【问题讨论】:

  • {"Target" : freq_dict} 不工作吗?
  • 嗯 'store1': 'door: 1', 'sound: 2', etc.
  • 我需要一些方法来识别哪个字典​​属于哪个商店
  • 请澄清您的具体问题或添加其他详细信息以准确突出您的需要。正如目前所写的那样,很难准确地说出你在问什么。请参阅How to Ask 页面以获得澄清此问题的帮助。
  • 对不起,让我澄清一下:{"Target": freq_dict} 确实让我到达了我需要去的地方 - 我怎样才能将变量 'store' 传递到该语法中,使其变为 {"Target" : freq_dict}、{"Shopko": freq_dict} 等,基于我传递给“商店”的值

标签: python dictionary key keyvaluepair


【解决方案1】:
// I suppose your store of sentences is in this format
store = {'store_name': cleaned_word_string}


store_dict = {}
for store_name in store:
    store_dict[store_name] = get_freq_dict(store_dict[store_name])


def get_freq_dict(cleaned_word_string):

    stop_words = set(stopwords.words('english'))
    word_tokens = word_tokenize(cleaned_word_string)
    filtered_sentence = [w for w in word_tokens if not w in stop_words]
    fw_freq = nltk.FreqDist(filtered_sentence).most_common()
    freq_dict = dict(fw_freq)
    return freq_dict

【讨论】:

    猜你喜欢
    • 2014-10-02
    • 2016-11-20
    • 1970-01-01
    • 2017-05-05
    • 2016-09-03
    • 2021-06-25
    • 1970-01-01
    • 1970-01-01
    • 2016-07-11
    相关资源
    最近更新 更多