More Python
Last modified
From Last Class
- In Python there is
no difference
between
"string"
and'string'
-
String concatination can be performed without the
+
operator:>>> "hello " 'world' 'hello world'
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
- strings can be split into lists
- lists and tuples are sequence types and can be indexed and sliced
- dictionaries can be converted to lists of tuples
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]))