Feed on
Posts
Comments

Archive for the 'Python' Category

to strip all the non-letters from a python string named ‘my_str’, you can use the following one-liner:
”.join([c for c in my_str if c.isalpha()])
to strip all the non-alphanumeric characters from that python string, use the slightly modified:
”.join([c for c in my_str if c.isalnum()])

to do string substitutions in python, use the “re” module and the “sub” function:
>>> import re

>>> test = “2545423/1-4242:0.3245″
>>> test ; re.sub(”/\d-\d*:”,”:”,test)
‘2545423/1-4242:0.3245′
‘2545423:0.3245′
and, to match a group and then use it in the substitution, use parentheses and the \<number> operation:
>>> new_boot_s = re.sub(”(\d+:)”,”n\\1″,boot_s)

if you call a shell process from python, your script will normally trundle along without pausing for that process to complete.  if you’d like the process to finish before your script continues on, use the communicate method:
proc = sub.Popen(my_job,stdout=sub.PIPE)
stdout,stderr = proc.communicate()

to get the full pathname to a script that python is executing, use the handy little one-liner:
>> os.path.abspath(sys.argv[0])

give a file a unique id in python

to hash a file’s contents in python, you can use the md5 module. this comes in handy if you want to screen a directory for duplicate files, for instance.
import md5
my_f = open(”my.file”)
my_s = my_f.read()
my_f.close()
my_hash = md5.new(my_s).hexdigest()

to custom sort a list on the fly, try using the lambda function to do a quick definition of the cmp function.  for instance, to sort the list ‘ids’, using each ‘id’ value in an ancillary dictionary ‘id_dict’:
ids.sort(cmp=lambda a,b:id_dict[b] - id_dict[a])

let’s say you’ve got a list of the numbers 0 through 4 and you wanted all 32 possible combinations of them.  to get that list:
list_of_five = range(0,5)   
swap_list_list = [[]]
for swap in list_of_five:
    temp_lists = []
    for list_stub in swap_list_list:
        this_list = copy.copy(list_stub)
        this_list.append(swap)
        temp_lists.append(this_list)
temp_lists.append(list_stub)
    swap_list_list = temp_lists
print swap_list_list
 
 

sort a python dictionary

let’s say you’ve got a dictionary keyed by strings and whose values are numbers.  if you’d like to sort those keys by those values, here’s a quick way to do so: my_dict_to_sort.sort(cmp=lambda a,b: cmp(a[1],b[1])) 

when you execute a program in python, the program’s name can be found with the following command: 
import sys 
print sys.argv[0]

 to get the full path to the program, use the abspath command: 
import os 
os.path.abspath(sys.argv[0])
 

to make a file executable from python, use the following template:
 >> import os>> my_filename = “file.txt”>> os.chmod(my_filename,0755)

Next »

More blogs about http://desk.stinkpot.org:8080/tricks.