【问题标题】:Python Count UNIQUE occurences...not total count. HOW?Python Count UNIQUE 出现...不是总数。如何?
【发布时间】:2014-09-05 00:29:14
【问题描述】:

更新:以下代码似乎可以解决问题:

        for word in words:
            if word not in unique_words: ##skips replicates in a given list
                unique_words.append(word)   

对于我的一生,我无法弄清楚如何计算一个单词在列表中的数量,而不是在列表中找到一个单词的次数。

如果我设置一个计数器...它会计算单词的出现次数。但是,我需要一些东西,因为它遍历单词列表(每个列表都是一条推文),计算一个单词的 UNIQUE 出现次数(例如,包含该单词的推文数量)。计数器,我知道如何使用它们,并且与集合 Counter...count 所有实例相同。

仅供参考...循环迭代的是推文,每个推文都应用了 .split() 函数...所以,每条推文都是单词列表。

这是我的代码没有做我需要做的事情。

        sentiment = 0   

        for word in words:
            if word in AFINN:
                sentiment += AFINN[word]                

        for word in words:
            if word not in AFINN and word not in new_sent:
                new_sent[word] = sentiment
                tweet_count[word] = 1

            elif word in new_sent:
                new_sent[word] = new_sent[word] + sentiment
                tweet_count[word] += 1

另外...我有两个单词的陈述,因为这是我能够获得总情绪分数的唯一方法,而不仅仅是找到新单词的分数。不过,我在想,如果我“回归”情绪,我可能不需要双循环?但是,就目前而言,这不是我最关心的问题。

谢谢!!!

【问题讨论】:

标签: python count unique counter tweets


【解决方案1】:

如果我理解正确的话,你有一堆推文,你想检查某个词在这些推文中出现了多少次?

count = 0
for tweet in tweets:
    if word in tweet:
        count += 1

当然,如果你真的不想冗长的话......

sum([word in tweet for tweet in tweets])

protip:试试 sum([True, True, True, False, True])

如果我误解了什么,请告诉我。

【讨论】:

    【解决方案2】:

    怎么样:

    tweets_with_word = defaultdict(int)
    
    for words in tweets:  # `tweets` is the "outside" list of word lists
        for word in set(words):
            tweets_with_word[word] += 1
    
        for word in words:
            ...  # The rest of your code
    

    基本上,使用set() 获取每条推文中唯一单词的列表,然后只计算这些实例。

    【讨论】:

    • 我无法备份到“推文中的单词”,因为它们不匹配……单词已被擦除、小写和拆分……并重命名为“单词”。而且我不想要推文中的所有独特词......我想要包含不在 AFINN 中的词的折叠推文。所以,按照描述使用 set() 并不能满足我的需要。
    • 我认为 Kirk Strauser 的版本是你想要的。如果你想排除单词,你总是可以做一个设置差异,例如,set(['hello', 'there', 'world']) - set(['there'])
    【解决方案3】:

    在您写的更新中(在您帖子的开头):

    for word in words: if word not in unique_words: ##skips replicates in a given list unique_words.append(word)

    现在我很困惑。如果这正是你想要的,那为什么不直接使用collections.OrderedDict

    from collections import OrderedDict words = ['good', 'good', 'bad', 'terrible', 'lucky'] unique_words = OrderedDict.fromkeys(words)

    不需要所有这些控制结构。

    如果单词的顺序无关紧要,那么只需使用set

    unique_words = set(words)

    【讨论】:

    • 我想过从键中复制...但我需要的是包含新词的推文数量。复制键/集只会给我这个词......复制值会给我出现的总数。但是,通过循环浏览推文,我会为每条包含 AFINN-111 列表中未包含的单词的推文获得 +1。目标是通过以下公式为不在 AFINN 中的每个单词得出情绪分数:E(推文发送分数)/(包含单词的推文计数),其中 E 是所有包含单词的推文的总和。是否有其他方法可以实现相同的目标?
    • 顺便说一句...我无法备份到“推文中的文字”,因为它们不匹配...这些文字已被擦除、小写并拆分...并重命名“词”。
    猜你喜欢
    • 2021-03-28
    • 2012-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-11
    • 1970-01-01
    • 1970-01-01
    • 2021-08-01
    相关资源
    最近更新 更多