python基礎

[python ]python基礎

!/usr/local/bin/python
# -*- coding: utf-8 -*-

################################################################################
#import
################################################################################
import re #正規表現

################################################################################
#code
################################################################################
#文字列
print u"******************** 文字列" 
s = "abcdefg" 
print len(s)                        #7
print s[-1]                         #g
print s[-2]                         #f
print s[0:3]                        #abc
print s[:3]                         #abc
print s[1:3]                        #bc
print s[1:]                         #bcdefg
print s[:]                          #abcdefg
print s + "hijk"                    #abcdefghijk
print "ab" * 3                      #ababab
print s.find("cd")                  #2
print s.replace("ab","xy")          #xycdefg
print s.upper()                     #ABCDEFG
print s.isalpha()                   #True
print s.isdigit()                   #False
print u"日本語"                     #日本語、ユニコード
print "\\"                          #\、エスケープシーケンス
print r"\\"                         #\\、raw文字列
print "abcd\n".rstrip()             #abcd、改行を削除
print "aa bb cc dd".split()         #['aa', 'bb', 'cc', 'dd']
print "aa,bb,cc,dd".split(",")      #['aa', 'bb', 'cc', 'dd']


print u"******************** 正規表現" 
#正規表現、import re 
match = re.match('Hello[\t]*(.*)world','Hello   Python world') 
print match.group(1)         #Python


print u"******************** リスト" 
#リスト
l = [1,2,3,4,5] 
print l[0:]                  #[1,2,3,4,5]
print l[2:]                  #[3,4,5]
print l[1:3]                 #[2,3]
print l[:3]                  #[1,2,3]
print l[-1]                  #5
print l + [6,7]              #[1,2,3,4,5,6,7]
l.append(6) 
print l                      #[1,2,3,4,5,6]
l.pop() 
print l                      #[1,2,3,4,5]

l1 = ["bb","aa","dd"] 
l1.sort() 
print l1 
l1.reverse() 
print l1 

#multi colum sort
ml = []
ml.append({'a':30,'b':20,'c':10})
ml.append({'a':10,'b':10,'c':10})
ml.append({'a':10,'b':20,'c':30})
for v in sorted(ml,key=lambda x:(x.get('c'),-x.get('a'))):
    print v

#index sort
l = []
l.append([4,9,3])
l.append([6,8,1])
l.append([5,7,1])
for k in sorted(l, key=lambda x:(x[2],x[1])):
    print k

#ネスト
m = [[1,2,3],[4,5,6],[7,8,9]] 
print m[1][2] 

#リスト内表記
col2 = [row[1] for row in m] 
print col2 

print u"******************** ディクショナリ" 
#ディクショナリ
d = {"a":1,"b":2} 
print d["a"] 
d["a"] += 1 
print d["a"] 

d1={} 
d1["b"] = 1 
d1["a"] = 2 
d1["c"] = 3 
print d1 

if not d1.has_key("d"):
  print u"key:[d]は存在しない" 

#キー
ks =d1.keys() 
print ks 
ks.reverse() 
print ks 
ks.sort() 
print ks 

for x in ks:
  print x 

d2 = {"d":1,"a":2,"b":3} 

for x in sorted(d2):
  print x 

#ネスト
rec={
     "name":{"first":"Bob","last":"Smith"},
     "job":["dev","mgr"],
     "age":40.5
} 

print rec["name"]["first"] 
print rec["job"][0] 
print rec["job"].append("janitor") 
print rec["age"] 
print rec 

dic = {}
dic["C"]=300
dic["A"]=200
dic["B"]=100
print dic

#key sort
for k,v in sorted(dic.items()):
    print "%s %d" % (k,v)

for k,v in sorted(dic.items(),reverse=True):
    print "%s %d" % (k,v)

#value sort
for k,v in sorted(dic.items(), key=lambda x:x[1]):
    print "%s %s" % (k,str(v))

for k,v in sorted(dic.items(), key=lambda x:x[1], reverse=True):
    print "%s %s" % (k,str(v))

print u"******************** タプル" 
#タプル、変更不可
tp = (1,2,3,4) 
print tp[2] 


print u"******************** ファイル" 
f=open("test.txt") 
bytes = f.read() 
print unicode(bytes,"UTF-8") 
f.close() 


f=open("test.txt") 
for x in f.readlines():
    print unicode( x.rstrip(),"UTF-8") 

f.close() 

f = open("test2.txt","w")
f.write("test1\n") 
f.write("test2\n") 
f.close() 


print u"******************** map関数" 
li = [1,2,3,4]
res = map((lambda x:x*3),li)
print res


print u"******************** filter関数" 
li = [1,2,3,4]
res = filter((lambda x:x<3),li)
print res


print u"******************** reduce関数" 
li = [1,2,3,4,5,6,7,8,9,10]
res = reduce((lambda x,y:x+y),li)
print res


print u"******************** リスト内表記" 
li = [1,2,3,4] 
res = [x*2 for x in li]
print res

res = [x*2 for x in li if x % 2 == 0]
print res


print u"******************** command" 
import os
print os.system("dir")


print u"******************** set関数"
s1 = set()
s1.add(1)
s1.add(2)
s1.add(3)
s1.add(3)
s1.add(4)
print s1
print 2 in s1
s1.remove(4)
print s1

s2 = set()
s2.add(2)
s2.add(3)
s2.add(4)
s2.add(5)
s2.add(6)

print s1.union(s2)                  #論理和
print s1.intersection(s2)           #論理積
print s1.difference(s2)             #差集合
print s1.symmetric_difference(s2)   #対象差

#集合演算子
print s1 | s2                       #論理和
print s1 & s2                       #論理積
print s1 - s2                       #差集合
print s1 ^ s2                       #対象差

----------------------------------------------------------
__author__ = 'develop'
import datetime
import glob
import os
from test_class import test_class
from test_class import test_class_ex

#python3-test
def main():
    print("----------> test-start")

    #ファイルリスト取得
    print("----------> filelist-get")
    files = glob.glob(".\data\*.txt")
    for f in files:
        print(f)

    dic={}
    list=[]
    #ファイル読み込み、withでcloseを自動で呼ばれる

    print("----------> file-read")
    with open(".\data\csv_data_utf8.txt", encoding='utf8') as rf:
        for l in rf:
            #文字列分割
            line = l.rstrip()   #改行削除
            datas = line.split(',')
            print ("{0} - {1} - {2}".format(datas[0],datas[1],datas[2]))
            list.append(datas[0])
            dic[datas[0]] = line

    #ファイルの書き込み、withでcloseを自動で呼ばれる
    print("----------> file-write")
    with open(".\data\csv_data_utf8_out.txt", encoding='utf8', mode="w") as
wf:
        for l in list:
            wf.write(l + "\n")

        for k,v in sorted(dic.items()):
            wf.write(v + "\n")

    #辞書ソート
    print("----------> dic sort")
    #key sort
    print("-----> dic key sort")
    for k,v in sorted(dic.items()):
        print( "{0} - {1}".format(k,v))

    #key sort reverse
    print("-----> dic key sort reverse")
    for k,v in sorted(dic.items(),reverse=True):
        print( "{0} - {1}".format(k,v))

    #value sort
    print("-----> dic value sort")
    for k,v in sorted(dic.items(), key=lambda x:x[1]):
        print( "{0} - {1}".format(k,v))

    #value sort reverse
    print("-----> dic value sort reverse")
    for k,v in sorted(dic.items(), key=lambda x:x[1], reverse=True):
        print( "{0} - {1}".format(k,v))

    #複数カラムソート
    print("----------> 複数カラムソート")
    l = []
    l.append([4,9,3])
    l.append([6,8,1])
    l.append([5,7,1])
    for k in sorted(l, key=lambda x:(x[2],x[1])):
       print(k)

    #文法
    print("----------> 文法")
    #if (or,and)
    value = 2
    if value == 1:
        print ("value=1")
    elif value == 2:
        print ("value=2")
    elif value ==2 or value == 1:
        print ("value=1 または 2")
    else:
        print ("value=1,2以外")

    #for
    for_sample=[]
    for_sample.append(1)
    for_sample.append(2)
    for_sample.append(3)
    for v in for_sample:
        print(v)

    for num in range(3):
        if num %2 == 0:
            print(num)

    #while
    count=0
    while count < 3:
        count+=1
        print (count)


    #例外
    try:
        result = 0
        print("処理開始")
        result = "abb" + 0
        print(result)
    except:
        print("例外処理")
        #print("----------------------------------------")
        #print (traceback.format_exc(sys.exc_info()[2]))
        #print("----------------------------------------")
    finally:
        print("処理完了")

    #文字列操作
    print("----------> 文字列操作")
    num = 100
    print(str(num))

    #パッディング
    print (str(num).rjust(10,"0"))

    #文字検索
    test_search_str = "abcdefg"
    print (str(test_search_str.find("cd")))

    #大文字小文字変換
    test_ul_str = "aBcD"
    print(test_ul_str.upper())
    print(test_ul_str.lower())

    #trim
    test_trim_str = "   python   "
    print("a_" + test_trim_str.lstrip() + "_z") #左削除
    print("a_" + test_trim_str.rstrip())        #右削除
    print("a_" + test_trim_str.strip() + "_z")  #右左削除

    #datetime
    print(datetime.datetime.today())

    #join
    datas = ("1","2","3","4")
    print(",".join(datas))

    #class test
    print("----------> classのテスト")
    tc = test_class("このテキスト")
    tc.show_txt()
    tce = test_class_ex("継承クラス")
    tce.show_txt2()


    #xmlパース
    print("----------> xmlパース")
    import xml.etree.cElementTree as etree
    tree = etree.parse("data/feed.xml")
    root = tree.getroot()
    print (root.tag)

    for child in root: #root直下のタグリスト
        print(child)

    print ("-----> enrtrys")
    entrys = root.findall("{http://www.w3.org/2005/Atom}entry")
    for entry in entrys:
        #title
        title = entry.find("{http://www.w3.org/2005/Atom}title")
        print (title.text)


#main
if __name__ == "__main__":
    main()