【问题标题】:'dict' object has no attribute 'union''dict' 对象没有属性 'union'
【发布时间】:2014-02-08 20:58:52
【问题描述】:

我有 wdict 作为字典,我想将所有唯一的单词添加到其中,这些单词是从存储在 path 的文本文件中扫描并由 CleanDoc() 转换为单词列表的。 我收到错误 AttributeError: 'dict' object has no attribute 'union'。我该怎么办?

import collections
import os.path
import glob
import nltk

wdict = {}
path = "C://Python27//Corpus Files//*.*"


#this function cleans up a doc (removes stopwords etc)
def cleanDoc(doc):
    stopset = set(nltk.corpus.stopwords.words('english'))
    stemmer = nltk.PorterStemmer()
    tokens = nltk.WordPunctTokenizer().tokenize(doc)
    clean = [token.lower() for token in tokens if token.lower() not in stopset and len(token) > 3 and token.isalpha() and not 'reuter']
    final = [stemmer.stem(word) for word in clean]
    return final

for text in glob.glob(path):
    f = open(text)
    data= f.read()
    words = cleanDoc(data)
    wdict = wdict.union(words)
    print wdict

【问题讨论】:

  • 看看dict APIdict 没有 union 方法。
  • 请注意(一旦将其设为set),您将在尝试分配给global 时获得UnboundLocalError,而无需声明它。

标签: python dictionary union corpus


【解决方案1】:

您可以使用set 代替dict

wdict = set() # `wset` will make a better name

也可能wdict.update(words) 看起来比wdict = wdict.union(words) 更好

【讨论】:

  • 需要明确的是,python 中没有“空集文字”,因此创建空集的唯一方法是使用set()
  • @Nigel Tufnel:wdict.update(words) 返回 None,因此您不能将其分配给变量,而 wdict.union(words) 返回更新后的集合。
  • @superjump 是的,这就是为什么他们在 update 调用前取消了 wdict =
  • 如果您将wdict 从字典更改为集合,最好也更改其名称,拥有一个实际上不是字典的变量wdict 可能会造成混淆。
【解决方案2】:

Python Dictionary 对象没有联合方法。 正如错误中所建议的那样。 Union 方法仅适用于 Sets。

您应该查看 SO 答案:- How to merge two Python dictionaries in a single expression?

我最喜欢的是:-

w_dicts.update(单词)

但这纯粹是个人选择。

希望这会有所帮助。

【讨论】:

  • 注意他们实际上是在使用集合,他们认为{} 创建了一个空集合,而不是一个空字典。这确实是这里的错误。
【解决方案3】:

wdict = {} 更改为wdict = set()

【讨论】:

  • 它有效,但我想合并所有文档中的单词,例如扩展或附加。
猜你喜欢
  • 2017-03-30
  • 2012-01-12
  • 2021-03-08
  • 2017-05-12
  • 2019-03-11
  • 1970-01-01
  • 1970-01-01
  • 2022-12-29
  • 2018-09-02
相关资源
最近更新 更多