import string
with open("letters.txt", "w") as file:
for l in string.ascii_lowercase:
file.write(l + "\n")
import string, os
if not os.path.exists("AtoZ"):
os.makedirs("AtoZ")
for letter in string.ascii_uppercase:
with open("AtoZ/" + letter + ".txt", "w") as file:
file.write( letter + "\n")
先判斷將被執行的程式目錄中是否有AtoZ的資料匣,沒有的話先做一個,然後把相關檔案產生致該資料匣中。
上面的練習是在AtoZ 資料匣中寫入A到Z的字母檔案,下面是把該資料匣中的文字讀入,並放到list裡
import glob
letters = []
file_list = glob.glob("AtoZ/*.txt")
for filename in file_list:
with open(filename, 'r') as file:
letters.append(file.read().strip('\n'))
print(letters)
#['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
這邊使用glob,用來搜尋資料匣中的文件,使用glob可以像在linux中使用find指令,例如在執行此python 程式的路徑中,有AtoZ的資料匣,則在linux 的console中,可以下 find AtoZ/*.txt
列出所以有AtoZ中txt檔案。
用 def 來建立function,不需要像java 指定回傳型別
def function(a, b):
print('infunction a+b:', a + b )
print('call function(3,4):', function(3, 4))
#infunction a+b: 7
#cll function(3,4): None
def function(a, b):
print('infunction a+b:', a + b )
print('call function():', function())
#TypeError: function() missing 2 required positional arguments: 'a' and 'b'
def function(a = 1, b = 2):
return a + b
print(type(function))
#用type()來看function
#<class 'function'>
print(type(function(3,4)))
#<class 'int'>
print(function())
#3
#沒帶參數,使用預設的a = 1, b = 2
print(function(3, 4))
#7
def function(a =1 , b):
return a + b
print(function(3, 4))
# def function(a =1 , b):
# ^
#SyntaxError: non-default argument follows default argument
c = 1
def function():
return c
c = 3
print('value from call function :', function())
#value from call function : 3
c = 1
def function():
c = 2
return c
c = 3
print('value from call function :',function())
#value from call function : 2
def function():
global va
va = 99
return va
try:
print('get va value before call function :',va)
except Exception as exp:
print(type(exp))
print(exp.args)
function()
print('get va value after call function :',va)
#<class 'NameError'>
#("name 'va' is not defined",)
#get va value after call function : 99
在執行function前先印一次va,此區塊用try except包起來;執行到這邊時會發生錯誤,原因是「name ‘va’ is not defined」。 執行functino後再印一次va,這時va有存在並可以印出值。
def words_count(string, splitter = None):
word_list = string.split(splitter)
return len(word_list)
print('split with blank, words count:', words_count("python is A:good, B:great!"))
print('split with [,], words count:',words_count("python is A:good, B:great!", ','))
#split with blank, words count: 4
#split with [,], words count: 2
這邊的words_count可帶2個參數,第一個是要計算字數的字串,後面的參數是要以什麼符號作為切分單位。沒有傳入時帶入None。
使用split()沒帶參數預設以空白為切分單位,所以第一次words_count沒帶參數,會切成4個字,第2次使用「,」會切成2個字。
wordA.txt
I have a pen, I hava a pencil.
def words_count(filepath):
with open(filepath, 'r') as file:
string = file.read()
print("sentence in txt file:", string)
strng_list = string.split()
return len(strng_list)
print("sentence words count in txt file:", words_count("wordsA.txt"))
#sentence in txt file I have a pen, I hava a pencil.
#sentence words count in txt file 8
def words_count(string):
string_list = string.split()
print('直接split,沒有排除符號連文字的情況:', string_list)
print('字數:',len(string_list))
string = string.replace(",", " ")
string_list = string.split()
print('把符號替換成空白在split:', string_list)
print('字數:',len(string_list))
words_count("I like coffee, wine,and milk.")
#直接split,沒有排除符號連文字的情況: ['I', 'like', 'coffee,', 'wine,and', 'milk.']
#字數: 5
#把符號替換成空白在split: ['I', 'like', 'coffee', 'wine', 'and', 'milk.']
#字數: 6
import re
def words_count(string):
string = re.sub('[,]', ' ', string)
print(string)
string_list = string.split()
print('直接split,把符號替換成空白:', string_list)
print('字數:',len(string_list))
words_count("I like coffee, wine,and milk.")
#I like coffee wine and milk.
#直接split,把符號替換成空白: ['I', 'like', 'coffee', 'wine', 'and', 'milk.']
#字數: 6
方式一
diction = {'a':1, 'b':2}
print(diction)
#{'a': 1, 'b': 2}
方式二
diction = dict(c = 3, d = 4)
print(diction)
#{'c': 3, 'd': 4}
使用 Java 8 的 Predicate,可以先針對特定class的過濾條件。 在需要使用不同條件篩選出list的結果時,可以重複套用,或組合套用。
[Customers]
LastName | Gender | Age | LastAmount | TotalBuyCount |
---|---|---|---|---|
Bee | M | 23 | 10000.0 | 5 |
Horse | F | 13 | 300.0 | 2 |
Monkey | M | 43 | 100.0 | 1 |
Leopard | M | 23 | 40000.0 | 10 |
Moose | F | 19 | 700.0 | 7 |
Frog | M | 23 | 2300.0 | 5 |
Rat | M | 63 | 9000.0 | 2 |
Goose | M | 70 | 4000.0 | 8 |
Seal | F | 15 | 670.0 | 1 |
Jaguar | M | 45 | 100000.0 | 39 |
characters = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"]
print("characters[4:7] => {}".format( characters[4:7] ))
#characters[4:7] => ['e', 'f', 'g']
區間是由第4的元素「e」到第7個元素(不包含第7個),所以最後只會拿到g(第6個元素)
用Stream找到List裡面第一個符合條件的物件,用Optional來接查找後的結果。
下表是不同條件的商品規則,這邊要來用Stream來取得搜尋條件中符合的第一個項目。
ProductRule ruleA = new ProductRule("001", "cake BANANA", "TWD", "Y");
ProductRule ruleB = new ProductRule("002", "cake APPLE", "TWD", "Y");
ProductRule ruleC = new ProductRule("003", "cake GRAPE", "JPY", "N");
ProductRule ruleD = new ProductRule("004", "cake ORANGE", "JPY", "N");
ProductRule ruleE = new ProductRule("005", "cake KIWI", "HKD", "N");
List<ProductRule> ruleList = new ArrayList<ProductRule>();
ruleList.add(ruleA);
ruleList.add(ruleB);
ruleList.add(ruleC);
ruleList.add(ruleD);
ruleList.add(ruleE);
用filter過濾條件,用peek印出進行每個項目時的情況,最後用findFirst()取得結果。