pythonテキスト処理の基礎練習と思想

7370 ワード

movies=["movies1","movies2","movies3"];

print(movies[1])

movies.insert(1,1975)

movies.insert(3,1795)

movies.insert(5,1985)

print(movies)

print("============for=============")
for item in movies:
    print(item)
print("============while=============")
count=0
while count<len(movies):
    print(movies[count])
    count=count+1;

print("============complex list=============")
movies2=["movie1",1952,["movie2",["movies3"]]]

for item in movies2:
    print(item);

print("============isinstance func(bif)=============")
for item in movies2:
    if isinstance(item,list):
        for item2 in item:
            print(item2)
    else:
        print(item)

print("============recursion=============")
def print_recurrence(the_lst):
    for item in the_lst:
        if isinstance(item,list):
            print_recurrence(item)
        else:
            print(item)

print_recurrence(movies2)

for num in range(5):
    print (num)

import sys

print("============stdout=============")
def print_recurrence(the_lst,indent=False,level=0,fn=sys.stdout):
    for item in the_lst:
        if isinstance(item,list):
            print_recurrence(item,indent,level+1,fn)
        else:
            if indent:
                for level_num in range(level):
                    print("\t",end='',file=fn)
            print(item,file=fn)

with open("test.txt","w") as data:
    print_recurrence(movies2,True,0,fn=data)

print("============using pickle=============")
import pickle
with open('mydata.pickle','wb') as mysavedata:
    pickle.dump([1,3,'test'],mysavedata)

with open('mydata.pickle','rb') as myrestoredata:
    lst=pickle.load(myrestoredata)

print(lst)

import os;

os.getcwd();

#    
manlst=[]
womenlst=[]
try:
    data=open('filetest.txt');
    for each_line in data:
        try:
            (role,words)=each_line.split(':',1)
            if role=='Man':
                manlst.append(words)
            elif role=='Women':
                womenlst.append(words)
        except ValueError:
            pass
    data.close()
except IOError:
    print("can't open file")

#     
try:
    tt="111";
    out=open("test.txt","w")
    wout=open("test2.txt","w+")
    print(manlst,file=out)
    print(womenlst,file=wout)
except IOError as err:
    print(str(err))
finally:
    out.close()
    wout.close()

# with        ,            
try:
    with open("test.txt","w") as out:
        print(manlst,file=out)
    with open("test2.txt","w") as wout:
        print(womenlst,file=wout)
except IOError as err:
    print(str(err))

# with          
try:
    with open("test.txt","w") as out,open("test2.txt","w") as wout:
        print(manlst,file=out)
        print(womenlst,file=wout)
except IOError as err:
    print(str(err))

#using pickle
import pickle
try:
    with open("test.txt","w") as out,open("test2.txt","w") as wout:
        pickle.dump(manlst,out)
        pickle.dump(womenlst,wout)
except IOError as err:
    print(str(err))
except pickle.PickleError as picErr:
    print("pickleError"+str(picErr))
    
data=[3,4,2,1,5,3,2]

print(data)

data2=sorted(data)

print(data2)

def sanitize(str):
    if '-' in str:
        spliter='-'
    elif ':' in str:
        spliter=':'
    else:
        return str

    (first,second)=str.split(spliter)

    return first+"."+second

try:
    with open('james.txt') as jamesfile:
        data=jamesfile.readline()
        james=data.strip().split(",")

    with open('julie.txt') as juliefile:
        data=juliefile.readline()
        julie=data.strip().split(",")
    with open('mikey.txt') as mikeyfile:
        data=mikeyfile.readline()
        mikey=data.strip().split(",")
    with open('sarah.txt') as sarahfile:
        data=sarahfile.readline()
        sarah=data.strip().split(",")
except IOError as ioerr:
    print("IOError"+str(ioerr))

clean_james=[]
#     
for item in james:
    clean_james.append(sanitize(item))

#          
clean_julie=[sanitize(item) for item in julie]
clean_mikey=[sanitize(item) for item in mikey]
clean_sarah=[sanitize(item) for item in sarah]
#set    ,    ,       
print(sorted(set(clean_james))[0:3])
print(sorted(set(clean_julie))[0:3])
print(sorted(set(clean_mikey))[0:3])
print(sorted(set(clean_sarah))[0:3])

#       
print("===========")
def getMinThreeNum(filename):
    try:
        with open(filename) as fileObj:
            data=fileObj.readline()
        dataArr=data.strip().split(",")
        result=sorted(set([sanitize(item) for item in dataArr]))[0:3]
        return result
    except IOError as ioerr:
        print("IOERROR:"+str(ioerr))
        return None

print(getMinThreeNum("james.txt"))

#dict    
movies={}
movies["m1"]="lao ren yu hai"
movies["m2"]="shi er shen xiao"
print(movies)
#            
def getMinThreeNum(filename):
    try:
        with open(filename) as fileObj:
            data=fileObj.readline()
        dataArr=data.strip().split(",")
        result=sorted(set([sanitize(item) for item in dataArr]))[0:3]
        return {'name':dataArr.pop(0),'dob':dataArr.pop(0),'times':dataArr}
    except IOError as ioerr:
        print("IOERROR:"+str(ioerr))
        return None

print(str(getMinThreeNum("james2.txt")))

#             
class Persion:
    def __init__(self,v_name,v_dob=None,v_times=[]):
        self.name=v_name
        self.dob=v_dob
        self.times=v_times
    def top3(self):
        return sorted(set([sanitize(item) for item in self.times]))[0:3]
    def add_time(self,time_vlaue):
        self.times.append(time_vlaue)
    def add_times(self,lst_time_value):
        self.times.extend(lst_time_value)


print("========class=================")
def getMinThreeNum2(filename):
    try:
        with open(filename) as fileObj:
            data=fileObj.readline()
        dataArr=data.strip().split(",")

        return Persion(dataArr.pop(0),dataArr.pop(0),dataArr)
    except IOError as ioerr:
        print("IOERROR:"+str(ioerr))
        return None
    except:
        print()

james2=getMinThreeNum2("james2.txt")
print(james2.top3())

class PersionLst(list):
    def __init__(self,v_name,v_dob=None):
        list.__init__([])
        self.name=v_name
        self.dob=v_dob
    def top3(self):
        return sorted(set([sanitize(item) for item in self]))[0:3]

print("========class extend=================")
def getMinThreeNum3(filename):
    try:
        with open(filename) as fileObj:
            data=fileObj.readline()
        dataArr=data.strip().split(",")
        temp=PersionLst(dataArr.pop(0),dataArr.pop(0))
        temp.extend(dataArr)
        return temp
    except IOError as ioerr:
        print("IOERROR:"+str(ioerr))
        return None
    except:
        print()


james3=getMinThreeNum3("james2.txt")
print(james3.top3())