【问题标题】:How to structure dictionary to apply to function with enumerate如何构造字典以应用于枚举函数
【发布时间】:2019-05-07 08:30:49
【问题描述】:

我正在尝试重新构建一个简单的函数,它要求将字典作为输入。无论我尝试什么,我都无法找出通过此函数的字典的最小工作示例。我读过字典,没有太多空间来创建不同的字典,因此我不知道问题出在哪里。

我尝试应用以下最少的字典示例:

import nltk

#Different dictionaries to try as minimum working examples:
comments1 = {1 : 'Rockies', 2: 'Red Sox'}
comments2 = {'key1' : 'Rockies', 'key2': 'Red Sox'}
comments3 = dict([(1, 3), (2, 3)])

#Function:
def tokenize_body(comments):
    tokens = {}
    for idx, com_id in enumerate(comments):
        body = comments[com_id]['body']
        tokenized = [x.lower() for x in nltk.word_tokenize(body)]
        tokens[com_id] = tokenized
    return tokens

tokens = tokenize_body(comments1)

我知道使用 enumerate 我基本上是在调用索引和键,但我不知道如何调用“正文”,即我想要标记的字符串。

对于以字符串作为输入的 cmets1cmets2 我收到错误:TypeError: string indices must be integers

如果我应用整数而不是字符串,cmets3,我会收到错误: TypeError: 'int' object is not subscriptable.

这对您来说可能看起来微不足道,但我无法弄清楚我做错了什么。如果您能提供一个最低限度的工作示例,我们将不胜感激。

【问题讨论】:

  • for idx, (com_id, com_body) in enumerate(comments.items()) 怎么样?
  • 不清楚你想在这里做什么。您确定要传入字典而不是列表吗?枚举一个字典没有多大意义。然后,一旦您进行迭代,您就可以调用comments[com_id],它会完全忽略枚举器。我认为您实际上根本不想枚举。另外请注意,您的任何字典都没有body 键,所以我不知道您想得到什么。
  • @DanielRoseman 这也是让我印象深刻的。我不明白“body”键的来源。此外,我无法用有效的“正文”重建任何字典。我从以下 github resporisory 中找到了该函数:[github.com/SmokinCaterpillar/doc2vec_user_comments/blob/master/… 不幸的是,没有关于数据结构的信息。
  • @Chris,这再次给出:TypeError:字符串索引必须是整数。
  • 是什么让您认为这些功能需要字典?在我看来,他们好像期待字典列表,所以就像[{'body': 'foo'}, {'body': 'bar'}]

标签: python dictionary tokenize enumerate


【解决方案1】:

为了在python中循环遍历一个字典,你需要使用items方法来获取键和值:

comments = {"key1": "word", "key2": "word2"}
def tokenize_body(comments):
    tokens = {}
    for key, value in comments.items():
        # values - word, word2
        # keys - key1, key2
        tokens[key] = [x.lower() for x in nltk.word_tokenize(value)]
    return tokens

enumerate用于列表,以获取元素的index

l = ['a', 'b']
for index, elm in enumerate(l):
    print(index) # => 0, 1

【讨论】:

    【解决方案2】:

    您可能正在寻找.items(),例如:

    for idx, item in enumerate(comments1.items()):
        print(idx, item)
    

    这将打印出来

    0 (1, 'Rockies')
    1 (2, 'Red Sox')
    

    a demo on ideone.com

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-22
      • 1970-01-01
      • 2011-08-20
      • 1970-01-01
      • 2011-10-30
      • 1970-01-01
      相关资源
      最近更新 更多