ECE 2524 - More Python

ECE 2524

Introduction to Unix for Engineers

More Python

Last modified

From Last Class

Some basic data structures

  • >>> import sys
    >>> mytuple = ( 5, 'five', sys.stdout)
  • >>> mylist = [ 1, 2, 3, 4 ]
  • dictionary (dict): collection of name, value pairs

    >>> mydict = { 'five': 5, 'two': 2, 'seven': 7 }

Data operations

Count Words

  • split input into list of words, add each word to a dictionary with the word as the key and the number of occurances is the value

Source

  • wordlist.py

    #!/usr/bin/env python3
    
    def word_list(stream):
        mywords = []
        for line in stream:
            for word in line.split():
                mywords.append(word)
    
        return mywords
    
    if __name__ == '__main__':
        from sys import stdin
    
        print(word_list(stdin))
  • pyfreq.py

    #!/usr/bin/env python3
    
    import wordlist as wl
    from sys import stdin,stdout
    
    words = {}
    
    for word in wl.word_list(stdin):
        try:
            words[word] += 1
        except KeyError:
            words[word] = 1
    
    for key in words:
        print("{0}: {1}".format(key, words[key]))

Homework

PyFreq Part 1