Analyze Top Twitter Mentions with Python Script

School
CUNY Hunter College**We aren't endorsed by this school
Course
CSCI 133.00
Subject
Computer Science
Date
Dec 11, 2024
Pages
1
Uploaded by haileyHS
import osdef cleanedup(s):alphabet = 'abcdefghijklmnopqrstuvwxyz0123456789@_'cleantext = ''for character in s.lower():if character in alphabet:cleantext += characterelse:cleantext += ' 'return cleantextdef findMentions(fileName):usernames = {}with open(fileName, encoding='utf-8') as file:for line in file:for word in cleanedup(line).split():if word.startswith('@'):usernames[word] = usernames.get(word, 0) + 1counts = [[count, word] for word, count in usernames.items()]counts.sort(reverse=True, key=lambda x: x[0])return counts[:3]directory = 'all-tweets'for filename in os.listdir(directory):if filename.endswith('.tweets'):filepath = os.path.join(directory, filename)print(filename)top_mentions = findMentions(filepath)for count, mention in sorted(top_mentions, key=lambda x: x[0]):print(" ", mention, count)
Background image