Skip to content

Instantly share code, notes, and snippets.

@alice1017
Created January 8, 2011 13:19
Show Gist options
  • Save alice1017/770826 to your computer and use it in GitHub Desktop.
Save alice1017/770826 to your computer and use it in GitHub Desktop.
my usefull module
#!/usr/bin/python
#coding:utf-8
"""this is very usefull Modules.
CLASSES:
File -- Make file object as you want.
DictSearch -- Search a dictionary.
FUNCTIONS:
checktype -- Check type of variable at argument.
choice -- Make random string.
dropN -- Delete "\\n" character from string or list of argument.
dropsame -- Delete same character from list of argument.
exp -- Expend a dictionary.
greplist -- Find a strings from list of argument.
geturllist -- Open a URL and insert contents into list.
todict -- Make a dictionary from variable of argument.
urlanalyze -- Analyze a URL string.
Please use help function to functions in this module, if you want to know more.
"""
# MODULES
import urllib
import random
import types
import os
import os.path
import pickle
# VARIABLES
__author__ = "Alice (http://twitter.com/Alice_Himmel)"
__version__ = "3.6.2"
__copyright__ = "Copyright (c) Alice"
__date__ = "2011/01/07"
String = types.StringType
List = types.ListType
Dict = types.DictType
Int = types.IntType
Float = types.FloatType
Unicode = types.UnicodeType
Tuple = types.TupleType
Func = types.FunctionType
Class = types.ClassType
Method = types.MethodType
Non_symbol = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz123456789"
Non_number = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz[]{}!$%&'()-^¥:;*+><"
Only_rome = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
Only_symbol = "[]{}!$%&'()-^¥:;*+><"
Only_numver = "123456789"
ALL = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz123456789[]{}!$%&'()-^¥:;*+><"
# CLASSES
class File:
"""this class can make file object as you want.
Please input file name at argument.
this class make dictionary of file status if you call this class.
Methods in this class call:
-- readonly
-- makefile
-- overwrite
-- writeonly
-- writeobj
-- loadobj
-- fpclose
status dictionary in:
-- access
-- path
-- size
-- extension
Please use help function to methods in this class, if you want to know more.
"""
def __init__(self,fname):
self.fname = fname
if os.access(self.fname,os.F_OK):
self.status = {}
self.status["access"] = True
self.status["path"] = os.getcwd()
self.status["size"] = os.path.getsize(self.fname)
self.status["extension"] = os.path.splitext(self.fname)[1]
else: self.status = {"access":False}
def changefile(self,fname):
"""this method change file of this file-class.
Please input file name at argument."""
self.fname = fname
if os.access(self.fname,os.F_OK):
self.status = {}
self.status["access"] = True
self.status["path"] = os.getcwd()
self.status["size"] = os.path.getsize(self.fname)
self.status["extension"] = os.path.splitext(self.fname)[1]
else: self.status = {"access":False}
def readonly(self):
"""make file object with READ mode.
Please do 'fpclose' method after you use this method."""
return open(self.fname,"r")
def makefile(self):
"""make new file with WRITE mode.
return False if access-variable is True.
"""
if self.status["access"]:
return False
else:
self.fp = open(self.fname,"a")
self.fp.write("")
self.fp.close()
return True
def overwrite(self,string):
"""overwrite a file with OVERWRITE mode.
return False if access-variable is False.
Please input string at argument.
"""
if self.status["access"]:
self.fp = open(self.fname,"a+")
self.fp.write(string)
self.fp.close()
return True
else: return False
def writeonly(self,string):
"""write a file with WRITE mode.
return False if access-variable is False.
Please input string at argument.
"""
if self.status["access"]:
self.fp = open(self.fname,"w")
self.fp.write(string)
self.fp.close()
return True
else: return False
def othermode(self,mode=None):
"""make file object with OTHER mode.
if you don't write mode argument, this method make file object with nomal mode."""
if mode:
self.mode = mode
self.fp = open(self.fname,self.mode)
else:
self.fp = open(self.fname)
def writeobj(self,object):
"""write a object to file.
Please input object variable to argument."""
self.fp = open(self.fname,"w")
pickle.dump(object,self.fp)
self.fp.close()
def loadobj(self):
"""load a object from file.
return the loaded object name is "self.object" """
self.fp = open(self.fname)
self.object = pickle.load(self.fp)
self.fp.close()
def fpclose(self):
"""close a file object
Please call this method if you call 'readonly' method in class.
"""
self.fp.close()
class DictSearch():
"""Find Key and Values from Dictionary."""
def __init__(self,dict):
self.dict = dict
def findKey(self,string):
"""Search key."""
acs = self.dict.has_key(string)
if ( acs == True ):
print self.dict[string]
return self.dict[string]
else:
print "Sorry, '%s' is not found." % string
def findKeyString(self,string):
"""Search Key String."""
self.key = []
for i,j in self.dict.iteritems():
try:
unver = str(i).index(string)
self.key.append(i)
except:
pass
if len(self.key) == 0:
print "Sorry, can't not found."
else:
print self.key
return self.key
def findValue(self,string):
"""Search Value."""
self.element = {}
for i,j in self.dict.iteritems():
if ( str(j) == string ):
self.element[i] = j
else:
pass
if len(self.element) == 0:
print "'%s' is not found." % string
else:
print self.element
return self.element
# FUNCTIONS
def urlanalyze(urlstring):
"""Analyze URL string and return result at dictionary form.
data:
protocol -- string ex) http, ftp, etc
domain -- string ex) www.google.com, etc
dirs -- list ex) http://a.com/abc/def/ -> ["abc","def"]
filename -- string ex) http://a.com/a.html -> a.html
ext -- string ex) http://a.com/a.html -> html
parameter -- Dict ex) http://aaaa.com/aa.php?a=b -> {"a":"b"}
"""
dict = {}
sp = urlstring.split("/")
dict["protocol"] = sp[0][:-1]
dict["domain"] = sp[2]
dict["filename"] = sp[-1]
dict["ext"] = sp[-1].split(".")[-1]
if len(sp[3:-1])==0: dict["dirs"] = None
else: dict["dirs"] = sp[3:-1]
# get param
try:
p = dict["filename"].index("?")
strparam = dict["filename"][p+1:]
parameter = strparam.split("&")
param = {}
for i in parameter:
d = todict(i)
param[d.key] = d.value
dict["filename"] = dict["filename"].split("?")[0]
dict["parameter"] = param
except:
pass
return dict
def dropsame(list):
"""delete same item in argument list.
return False if argument is not list."""
if checktype(list,List):
item = []
for i in list:
if i not in item:
item.append(i)
return item
else:
return False
def geturllist(urlstring):
"""Open URL and return list that is file contents."""
ulist = []
up = urllib.urlopen(urlstring)
for i in up:
ulist.append(i)
return ulist
def todict(var,comment=None):
"""Convert dictionary from variable.
variable of the argument is string or list only.
the second argument is first letter of the list elements.
ex)
>>> list = [";aa=bb","bb=cc"]
>>> todict(list,";")
({"bb":"cc"},[";aa=bb"])
"""
class manage():
def __init__(self,string):
self.item = {}
sp = string.split("=")
if len(sp)==2:
self.key = sp[0].strip()
self.value = sp[1].strip()
self.item[self.key] = self.value
self.result = True
else:
self.result = False
if checktype(var,String):
m = manage(var)
return m.item
elif checktype(var,List):
if comment:
item = ({},[])
for i in var:
if i[0] == comment:
item[1].append(i.strip())
else:
m = manage(i)
if m.result:
item[0][m.key] = m.value
else:
pass
return item
else:
item = {}
for i in var:
m = manage(i)
if m.result:
item[m.key] = m.value
else:
pass
return item
def greplist(locallist,string):
"""Find string from list at second argument."""
findout = []
for line in locallist:
try:
out = ''.join(line).index(string)
instring = line.strip()
findout.append(instring)
except:
pass
if ( len(findout) == 0 ):
return False
elif len(findout) == 1:
return ''.join(findout)
else:
return findout
def dropN(var):
"""Delete a "\\n" string in variable that argument
variable is list or string only."""
if checktype(var,List):
while "\n" in var:
var.remove("\n")
elif checktype(var,String):
l = list(var)
while "\n" in l:
l.remove("\n")
var = ''.join(l)
return var
def checktype(var,argtype=None):
"""Check type of variable in arguments.
arguments:
01 : var -- variable that you want to know type.
02 : type -- variable type.
** this function print type if you don't input type argument.
types:
01 : String
02 : List
03 : Dict
04 : Int
05 : Float
06 : Unicode
07 : Tuple
08 : Func
09 : Class
10 : Method
11 : Nonetype
"""
if argtype:
return isinstance(var,argtype)
else:
print type(var)
def choice(num,mode=None):
"""make random string.
Please input number of the strings that you want to make random string at first argument.
And, the second argument is mode of this function.
here is more of the mode.
mode:
01 : Non_symbol -- Big and small rome string, number only.
02 : Non_number -- Big and small rome string, symbol only.
03 : Only_rome -- Big and small rome string only.
04 : Only_symbol -- Symbol only.
05 : Only_number -- Number only.
06 : ALL -- Big and small rome string, symbol, number.
"""
def make(num,str):
string = ""
for i in range(num):
x = random.choice(list(str))
string += x
return string
if mode:
return make(num,mode)
else:
return make(num,ALL)
def exp(dictionary):
"""Get keys and values from dictionary that argument, return tuple."""
item = ([],[])
for i,j in dictionary.iteritems():
item[0].append(i)
item[1].append(j)
return item
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment