Function to count hashtags

2020-06-25 04:57发布

问题:

I'm trying to get a function that counts and shows hashtags of a list.

Example input:

["Hey, im in the #pool",
 "beautiful #city",
 "#city is nice",
 "Have a nice #weekend",
 "#weekend <3",
 "Nice #"]

Output:

{"pool" : 1, "city" : 2, "weekend" : 2}

But if there is only a # followed by no words, it should not count as a hashtag. Same with stuff before the hashtag, something like „%#“ is not allowed to count as a hashtag. Hashtags are defined (a-z,A-Z,0-9) every other char ends the hashtag

My current code:

def analyze(posts):
    tag = {}
    for sentence in posts:
        words = sentence.split(' ')
        for word in words:
            if word.startswith('#'):
                if word[1:] in tag.keys():
                    tag[word[1:]] += 1
                else:
                    tag[word[1:]] = 1
    return(tag)


posts = ["Hey, im in the #pool",
         "beautiful #city",
         "#city is nice",
         "Have a nice #weekend",
         "#weekend <3",
         "Nice #"]
print(analyze(posts))

回答1:

In one pass with case insensitive regex search and collections.Counter object:

from collections import Counter
import re

lst = ["Hey, im in the #pool", "beautiful #city", "#city is nice",
       "Have a nice #weekend", "#weekend <3", "Nice #"]

hash_counts = Counter(re.findall(r'#([a-z0-9]+)', ' '.join(lst), re.I))
print(dict(hash_counts))

The output:

{'pool': 1, 'city': 2, 'weekend': 2}


回答2:

Use re with collections.Counter :

import re
from collections import Counter

data  = [ "Hey, im in the #pool",
  "beautiful #city",
  "#city is nice",
  "Have a nice #weekend",
  "#weekend <3",
  "Nice #" ]

count_hashtag = Counter()
for element in data:
    for hast_tag in re.findall('#(\w+)', element):
        count_hashtag[hast_tag] += 1

print(count_hashtag)
# Counter({'city': 2, 'weekend': 2, 'pool': 1})

If you want #City and #city equal:

  count_hashtag[hast_tag.casefold()] += 1


回答3:

Use this:

a = [ "Hey, im in the #pool",
  "beautiful #city",
  "#city is nice",
  "Have a nice #weekend",
  "#weekend <3",
  "Nice #"]
resdict = {}
for item in a:
    for word in item.split():
        if word.startswith('#') and len(word) != 1:
            if word.replace('#', '') not in resdict:
                resdict[word.replace('#', '')] = 1
            else: resdict[word.replace('#', '')] += 1
print(resdict)


回答4:

l = ["Hey, im in the #pool",
 "beautiful #city",
 "#city is nice",
 "Have a nice #weekend",
 "#weekend <3",
 "Nice #"]


from collections import defaultdict 
def func(l):

    dic = defaultdict(int)
    for i in l:
        for j in i.split():
            if j[0]=='#' and len(j)>1:
                dic[j[1:]]+=1
    return dict(dic)

print(func(l)) 

output

{'pool': 1, 'city': 2, 'weekend': 2}