# Count who's tweeting

# count tweets per twitter handle with a dictionary
def makeTweetDict():
    twFile = open("tweets.txt","r",encoding="utf-8")

    twDict = {} # start with empty dictionary
    for line in twFile:
        # header lines have a month in them
        if ("Jan" in line) or ("Feb" in line):
            # the handle is after the "@" character
            words = line.split("@")
            handle = words[1]
            handle = handle.strip()  # get rid of newline after handle

            # values in dictionary are number of times we've seen
            # that handle
            if handle in twDict:
                # if handle is already a key
                twDict[handle] = twDict[handle] + 1
            else:
                # first time this handle
                twDict[handle] = 1

    # the output of this function is the dictionary
    return twDict

# take dictionary as input and print out results nicely
def printOutData(twDict):

    # Put items into list, sort by counts

    # for loop on a dictionary
    # variable key is each key in turn
    L = []  # empty list
    for key in twDict:
        # run through all keys
        val = twDict[key]  # get value
        L.append( (val,key) )  # build up list of tuples
        
    # sort items by values
    L = sorted(L,reverse=True) # sort the list of tuples
    
    # now print it out nicely
    for pair in L:
        # each list element is a (value,key) tuple
        count = pair[0]
        tweeter = pair[1]
        print(tweeter,"tweeted",count,"times")
        
    return

def main():
    # two-function program again
    # read file and make dictionary
    tweeters = makeTweetDict()

    # take dictionary data and print it out nicely
    printOutData(tweeters)


main()
