•
•
•
•
What is DaniWeb IT Discussion Community?
You're currently browsing the Python section within the Software Development category of DaniWeb, a massive community of 391,590 software developers, web developers, Internet marketers, and tech gurus who are all enthusiastic about making contacts, networking, and learning from each other. In fact, there are 2,651 IT professionals currently interacting right now! Registration is free, only takes a minute and lets you enjoy all of the interactive features of the site.
Please support our Python advertiser:
Views: 51425 | Replies: 144
![]() |
An example for how to search a dictionary with key: value pairs for both the value and the key:
python Syntax (Toggle Plain Text)
# search a dictionary for key or value def find_key(dic, val): """return the key of dictionary dic given the value""" return [k for k, v in symbol_dic.iteritems() if v == val][0] def find_value(dic, key): """return the value of dictionary dic given the key""" return dic[key] # test it out if __name__ == '__main__': # dictionary of chemical symbols symbol_dic = { 'C': 'carbon', 'H': 'hydrogen', 'N': 'nitrogen', 'Li': 'lithium', 'Be': 'beryllium', 'B': 'boron' } print find_key(symbol_dic, 'boron') # B print find_value(symbol_dic, 'B') # boron
drink her pretty
Sometimes you just have to clear the display screen when you work with the Python command shell. This little function does that in both Windows or Linux:
You can save the whole module as clear_screen.py and import it into your program.
python Syntax (Toggle Plain Text)
def clear_screen(): """ clear the screen in the command shell works on windows (nt, xp, Vista) or linux """ import os os.system(['clear','cls'][os.name == 'nt']) # test module out if __name__ == '__main__': import time print "some text on the screen for a few seconds" # wait 2.5 seconds time.sleep(2.5) # now clear the screen clear_screen() # wait time.sleep(1.5) print "test completed" raw_input("press enter to go on ")
Last edited by ZZucker : Jan 29th, 2008 at 11:09 am.
Never argue with idiots, they'll just bring you down to their level and beat you with their experience.
•
•
Join Date: Oct 2004
Location: Mojave Desert
Posts: 2,394
Reputation:
Rep Power: 9
Solved Threads: 172
Just an updated way to count the frequency of letters in a text ...
You can rewrite the code to count words in a text.
The following code may not be simpler, but it is slightly faster then the set code ...
python Syntax (Toggle Plain Text)
# count the character frequency in a text: # create a list of unique (frequency, character) tuples # then sort and display highest frequency characters first text = 'mississippi mudslide' # create a list of characters from the text c_list = list(text) # make a list of (frequency, char) tuples, use set() to avoid duplicates fc_list = [(c_list.count(c), c) for c in set(c_list) if c.isalpha()] for item in sorted(fc_list, reverse=True): print "%s --> %s" % (item[1], item[0]) """ my output --> s --> 5 i --> 5 p --> 2 m --> 2 d --> 2 u --> 1 l --> 1 e --> 1 """
The following code may not be simpler, but it is slightly faster then the set code ...
python Syntax (Toggle Plain Text)
# count the character frequency in a text # a slightly faster option using a dictionary instead of a set ... from operator import itemgetter text = 'mississippi mudslide' d = {} for c in text: if c.isalpha(): d[c] = d.get(c, 0) + 1 for k, v in sorted(d.items(), key=itemgetter(1), reverse=True): print "%s --> %s" % (k, v) """ my output --> i --> 5 s --> 5 d --> 2 m --> 2 p --> 2 e --> 1 l --> 1 u --> 1 """
Last edited by vegaseat : Jan 31st, 2008 at 1:35 am. Reason: dict
May 'the Google' be with you!
You have two lists, one list with all the cities you wanted to visit in your life, and another list of cities you have already visited. Now you want to create a new list of cities you have not visited yet:
python Syntax (Toggle Plain Text)
# subtract/remove elements of one list from another city = ['Lisbon', 'Paris', 'Reno', 'London', 'Oslo', 'Ypsilanti'] visited = ['Reno', 'Ypsilanti'] not_visited = [c for c in city if c not in visited] # order of remaining elements has not changed print not_visited # simpler ... not_visited = list(set(city) - set(visited)) # order of remaining elements has changed print not_visited """ my result ---> ['Lisbon', 'Paris', 'London', 'Oslo'] ['Paris', 'Oslo', 'London', 'Lisbon'] """
Never argue with idiots, they'll just bring you down to their level and beat you with their experience.
•
•
Join Date: Feb 2008
Posts: 4
Reputation:
Rep Power: 0
Solved Threads: 0
•
•
•
•
One more function sample to show you that a function can decide internally what type of number to return. Also shows an example of try/except exception handling.
Click on "Toggle Plain Text" so you can highlight and copy the code to your editor without the line numbers.python Syntax (Toggle Plain Text)
# a function to return the numeric content of a cost item # for instance $12.99 or -$123456789.01 (deficit spenders) def getVal(txt): if txt[0] == "$": # remove leading dollar sign txt = txt[1:] if txt[1] == "$": # could be -$xxx txt = txt[0] + txt[2:] while txt: # select float or integer return try: f = float(txt) i = int(f) if f == i: return i return f except TypeError: # removes possible trailing stuff txt = txt[:-1] return 0 # test the function ... print getVal('-$123.45')
So, I was trying to go through this code and understand. But I have a few questions on it. And please bear with me I'm just starting to learn python.
txt = txt[0] + txt[2:]
Why did you add the two together?
I'm also confused on that while loop. Why do you retrun i, f, and 0. And what exactly is it doing line by line.
Any help would be much appreciated.
Thanks
Please follow the rules as set forth in:
http://www.daniweb.com/forums/post104844-2.html
Don't mess up this thread, start your own thread in the forum! I will anwer your questions there once you do that.
Last edited by vegaseat : Feb 24th, 2008 at 9:42 pm. Reason: follow 'start your own thread' rule
You can use the local variable dictionary vars() to create new variables on the fly:
Print vars() after line 1 and 2 to follow what's happening.
python Syntax (Toggle Plain Text)
food = 'bread' vars()[food] = 123 print bread # --> 123
No one died when Clinton lied.
A function to allow for a relatively secure input of dates:
Thanks to Jeff for the idea.
python Syntax (Toggle Plain Text)
# a more secure way to enter a date import datetime as dt def enter_date(): """ asks to enter year, month and day and returns date info as <type 'datetime.datetime'> """ def extract_date(s): try: # month given as a decimal number date = dt.datetime.strptime(s, "%d %m %Y") except: try: # month given as a 3 letter abreviation date = dt.datetime.strptime(s, "%d %b %Y") except: return None return date while True: year = raw_input("Enter year (eg. 1979): ") # you can enter number of month, full name or 3 letter abbreviation month = raw_input("Enter month (eg. 9 or sep): ") day = raw_input("Enter the day of the month: ") date = extract_date(day + " " + month[:3].title() + " " + year) if date == None: print "Illegal info!" continue else: return date date = enter_date() # testing ... #print date, type(date) # 2001-09-11 00:00:00 <type 'datetime.datetime'> #print date.strftime("%m/%d/%Y") # 09/11/2001 #print date.strftime("%d%b%Y") # 11Sep2001 # do something with it ... today = dt.datetime.today() age = today - date # assumes week starts with Monday weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] week_day = weekdays[dt.date.weekday(date)] print "Today is %s" % today.strftime("%d%b%Y") print "%s was %d days ago on a %s" % (date.strftime("%d%b%Y"), age.days, week_day) """ my output --> Enter year (eg. 1979): 2001 Enter month (eg. 9 or sep): september Enter the day of the month: 11 Today is 03Mar2008 11Sep2001 was 2365 days ago on a Tuesday """
Never argue with idiots, they'll just bring you down to their level and beat you with their experience.
Here is an example how to output a formatted table from a loop:
python Syntax (Toggle Plain Text)
# print a table (16 columns) of ASCII characters from 1 to 127 # Bumsfeld, thanks for the dictionary controls_dic = { 1: 'SOH', 2: 'STX', 3: 'ETX', 4: 'EOT', 5: 'ENQ', 6: 'ACK', 7: 'BEL', 8: 'BS', 9: 'HT', 10: 'LF', 11: 'VT', 12: 'FF', 13: 'CR', 14: 'SO', 15: 'SI', 16: 'DLE', 17: 'DC1', 18: 'DC2', 19: 'DC3', 20: 'DC4', 21: 'NAK', 22: 'SYN', 23: 'ETB', 24: 'CAN', 25: 'EM', 26: 'SUB', 27: 'ESC', 28: 'FS', 29: 'GS', 30: 'RS', 31: 'US'} n = 1 for k in range(1, 128): if k < 32: s = controls_dic[k] else: s = chr(k) if n % 16 > 0: print "%4s" % s, else: print "%4s" % s n += 1
Never argue with idiots, they'll just bring you down to their level and beat you with their experience.
This modified Tkinter GUI code allows you to follow your character key strokes on the console display:
python Syntax (Toggle Plain Text)
# KeyLogger.py # show a character key when pressed without using Enter key # hide the Tkinter GUI window, only console shows import Tkinter as tk def key(event): if event.keysym == 'Escape': root.destroy() print event.char root = tk.Tk() print "Press a key (Escape key to exit):" root.bind_all('<Key>', key) # don't show the tk window root.withdraw() root.mainloop()
No one died when Clinton lied.
![]() |
•
•
•
•
Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
•
•
•
•
•
•
•
•
DaniWeb Python Marketplace
- Clear the console screen (Python)
- Re: Starting Python (Python)
Other Threads in the Python Forum
- Previous Thread: Wizards Warlocks & Window.Refresh()
- Next Thread: Pygame Cursor



Linear Mode