Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Regex count company hashtags in a tweet (eg. $SPY)

I can count number of hashtags in a tweet with regex (eg. #APPL).

import re
from collections import Counter

def count_tags(tweet):
    pattern = '#[A-Za-z0-9]+'
    return len(re.findall(pattern,tweet))

print(count_tags('#TSLA #APPL #FB up today.'))
>>> 3

But I can’t seem to use same code to count the number of ticker tags (eg. $AAPL)?

import re
from collections import Counter

def count_tags(tweet):
    pattern = '$[A-Za-z0-9]+'
    return len(re.findall(pattern,tweet))

print(count_tags('$TSLA $APPL $FB up today.'))
>>> 0

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Since, $ is a regex symbol that means end of string so you need to escape your $ sign:

\$[A-Za-z0-9]+

Demo

Modified source:

import re
from collections import Counter

def count_tags(tweet):
    pattern = '\$[A-Za-z0-9]+'
    return len(re.findall(pattern,tweet))

print(count_tags('$TSLA $APPL $FB up today.'))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading