Function to count hashtags

旧巷老猫 提交于 2019-12-03 21:21:42

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}

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

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)
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}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!