# create a dic (Its a hash table) d = {} d['a'] = 'aaaaaaaa' d['b'] = 'bbbbbbbb' d['c'] = 'cccccccc' #retrive data from a dic print d['b'] #print d['x'] # if a key is not in the dic, then an error will occur print d.get('b'), "d.get('do not have this key') =", d.get('do not have this key') # determ if a key is in the dic print 'a' in d, 'x' in d # loop a dic for k in d.keys(): print 'key:', k, '=', d[k] for t in d.items(): print t ###################################################################################### # this will not work, just for memo. #import sys #def cat(filename): # f = open(filename, 'r') # read every line, dose not take too much memroy # for line in f: # print(line, end='') # read all content in a list, have to have at least that much memroy # lines = f.readlines() # print(lines) # read the whole file as a string # context = f.read() # print(context) # f.close() #def main(): # cat(sys.argv[1]) #if __name__ == '__main__': # main() ###################################################################################### #################################wordcount ########################################## #!/usr/bin/python -tt # Copyright 2010 Google Inc. # Licensed under the Apache License, Version 2.0 # http://www.apache.org/licenses/LICENSE-2.0 # Google's Python Class # http://code.google.com/edu/languages/google-python-class/ """Wordcount exercise Google's Python class The main() below is already defined and complete. It calls print_words() and print_top() functions which you write. 1. For the --count flag, implement a print_words(filename) function that counts how often each word appears in the text and prints: word1 count1 word2 count2 ... Print the above list in order sorted by word (python will sort punctuation to come before letters -- that's fine). Store all the words as lowercase, so 'The' and 'the' count as the same word. 2. For the --topcount flag, implement a print_top(filename) which is similar to print_words() but which prints just the top 20 most common words sorted so the most common word is first, then the next most common, and so on. Use str.split() (no arguments) to split on all whitespace. Workflow: don't build the whole program at once. Get it to an intermediate milestone and print your data structure and sys.exit(0). When that's working, try for the next milestone. Optional: define a helper function to avoid code duplication inside print_words() and print_top(). """ """ import sys # +++your code here+++ # Define print_words(filename) and print_top(filename) functions. # You could write a helper utility function that reads a file # and builds and returns a word/count dict for it. # Then print_words() and print_top() can just call the utility function. def constructDicFromFile(filename): f = open(filename) dic = {} text = f.read() words = text.split() for word in words: if word in dic: dic[word] = dic[word] + 1 else: dic[word] = 1 return dic def print_words(filename): dic = constructDicFromFile(filename) for x, y in dic.items(): print(x, y) def print_top(filename): dic = constructDicFromFile(filename) dicList = sorted(dic.items(), key=lastTupleVal, reverse=True) countor = 0 for wordPair in dicList: if 10 < countor: break; countor += 1 print(wordPair[0], wordPair[1]) def lastTupleVal(val): return val[-1] ### # This basic command line argument parsing code is provided and # calls the print_words() and print_top() functions which you must define. def main(): if len(sys.argv) != 3: print('usage: ./wordcount.py {--count | --topcount} file') sys.exit(1) option = sys.argv[1] filename = sys.argv[2] if option == '--count': print_words(filename) elif option == '--topcount': print_top(filename) else: print('unknown option: ' + option) sys.exit(1) if __name__ == '__main__': main() """ ########################################mimic########################################## """ #!/usr/bin/python -tt # Copyright 2010 Google Inc. # Licensed under the Apache License, Version 2.0 # http://www.apache.org/licenses/LICENSE-2.0 # Google's Python Class # http://code.google.com/edu/languages/google-python-class/ """Mimic pyquick exercise -- optional extra exercise. Google's Python Class Read in the file specified on the command line. Do a simple split() on whitespace to obtain all the words in the file. Rather than read the file line by line, it's easier to read it into one giant string and split it once. Build a "mimic" dict that maps each word that appears in the file to a list of all the words that immediately follow that word in the file. The list of words can be be in any order and should include duplicates. So for example the key "and" might have the list ["then", "best", "then", "after", ...] listing all the words which came after "and" in the text. We'll say that the empty string is what comes before the first word in the file. With the mimic dict, it's fairly easy to emit random text that mimics the original. Print a word, then look up what words might come next and pick one at random as the next work. Use the empty string as the first word to prime things. If we ever get stuck with a word that is not in the dict, go back to the empty string to keep things moving. Note: the standard python module 'random' includes a random.choice(list) method which picks a random element from a non-empty list. For fun, feed your program to itself as input. Could work on getting it to put in linebreaks around 70 columns, so the output looks better. """ import random import sys def mimic_dict(filename): """Returns mimic dict mapping each word to list of words which follow it.""" # +++your code here+++ f = open(filename) text = f.read() words = text.split() dic = {} for i in range(len(words)-1): if words[i] in dic: dic[words[i]].append(words[i+1]) else: dic[words[i]] = [words[i+1]] return dic def print_mimic(mimic_dict, word): """Given mimic dict and start word, prints 200 random words.""" # +++your code here+++ print(word, end=' ') for i in range(300): word = print_nextWord(mimic_dict, word) return def print_nextWord(mimic_dict, word): nextWord = random.choice(mimic_dict.get(word)) print(nextWord, end=' ') return nextWord # Provided main(), calls mimic_dict() and mimic() def main(): if len(sys.argv) != 2: print('usage: ./mimic.py file-to-read') sys.exit(1) dict = mimic_dict(sys.argv[1]) print_mimic(dict, 'Alice') if __name__ == '__main__': main() """
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question