0

我正在尝试查看公司列表中的公司是否在文件中的一行中。如果是,我利用该公司的索引来增加另一个数组中的变量。以下是我的python代码。我不断收到以下错误:AttributeError:“set”对象没有属性“index”。我无法弄清楚出了什么问题,并认为错误是被**包围的线。

companies={'white house black market', 'macy','nordstrom','filene','walmart'}
positives=[0 for x in xrange(len(companies))]
negatives=[0 for x in xrange(len(companies))]

for line in f:
    for company in companies:
        if company in line.lower():
            words=tokenize.word_tokenize(line)
            bag=bag_of_words(words)
            classif=classifier.classify(bag)
            if classif=='pos':
                **indice =companies.index(company)**
                positives[indice]+=1
            elif classif=='neg':
                **indice =companies.index(company)**
                negatives[indice]+=1 
4

3 回答 3

3
companies={'white house black market', 'macy','nordstrom','filene','walmart'}

是一套。它有独特的条目。

companies=['white house black market', 'macy','nordstrom','filene','walmart']

是一个列表,可以有多个相同值的条目。它也可以被索引。

于 2012-11-23T05:00:37.973 回答
2
companies={'white house black market', 'macy','nordstrom','filene','walmart'}

上面的声明是一个set. 而且由于 aset没有ordering,因此您无法从中获取任何元素的索引。

>>> d = {2, 3, 4, 5}
>>> d
set([2, 3, 4, 5])  # It is a Set

所以,要索引一个元素,它应该被声明为List: -

companies=['white house black market', 'macy','nordstrom','filene','walmart']
于 2012-11-23T05:01:15.323 回答
1

company 是一个集合,集合没有顺序,所以不能使用 index()。您可以将其更改为列表:

companies=['white house black market', 'macy','nordstrom','filene','walmart']
于 2012-11-23T05:00:05.690 回答