word_count = {} with open("./Beginner Guide to Python.txt") as fin: for line in fin: line = line[:-1] words = line.split() for word in words: if word not in word_count: word_count[word] = 0 word_count[word] += 1 print( sorted( word_count.items(), key=lambda x: x[1], reverse=True )[:10] )
def get_jiecheng(number): result = 1 while number > 0: result *= number number -= 1 return result print("jiecheng 6 = ", get_jiecheng(6)) print("jiecheng 3 = ", get_jiecheng(3)) print("jiecheng 100 = ", get_jiecheng(100))
import math def compute_area_of_circle(r): return round(math.pi * r * r, 2) print("area of 2 is: ", compute_area_of_circle(2)) print("area of 3.14 is: ", compute_area_of_circle(3.14)) print("area of 6.78 is: ", compute_area_of_circle(6.78))
def is_prime(number): if number in (1, 2): return True for idx in range(2, number): if number % idx == 0: return False return True def print_primes(begin, end): for number in range(begin, end + 1): if is_prime(number): print(f"{number} is a prime") begin = 11 end = 25 print_primes(begin, end)
def sum_of_square(n): result = 0 for number in range(1, n + 1): result += number * number return result print("sum of square 3: ", sum_of_square(3)) print("sum of square 5: ", sum_of_square(5)) print("sum of square 10: ", sum_of_square(10))
def sum_of_list(param_list): total = 0 for item in param_list: total += item return total list1 = [1, 2, 3, 4] list2 = [17, 5, 3, 5] print(f"sum of {list1}, ", sum_of_list(list1)) print(f"sum of {list2}, ", sum_of_list(list2)) print(f"sum of {list1}, ", sum(list1)) print(f"sum of {list2}, ", sum(list2))
def get_even_numbers(begin, end): result = [] for item in range(begin, end): if item % 2 == 0: result.append(item) return result begin = 4 end = 15 print(f"begin={begin}, end={end}, even numbers: ", get_even_numbers(begin, end)) data = [item for item in range(begin, end) if item % 2 == 0] print(f"begin={begin}, end={end}, even numbers: ", data)
def remove_elements_from_list(lista, listb): for item in listb: lista.remove(item) return lista lista = [3, 5, 7, 9, 11, 13] listb = [7, 11] print(f"from {lista} remove {listb}, result : ", remove_elements_from_list(lista, listb)) lista = [3, 5, 7, 9, 11, 13] listb = [7, 11] data = [item for item in lista if item not in listb] print(f"from {lista} remove {listb}, result : ", data)
def get_unique_list(lista): result = [] for item in lista: if item not in result: result.append(item) return result lista = [10, 20, 30, 10, 20] print(f"source list {lista}, unique list:", get_unique_list(lista)) print(f"source list {lista}, unique list:", list(set(lista)))
lista = [20, 40, 30, 50, 10] lista.sort(reverse=True) #listb = sorted(lista, reverse=True) print(f"lista is {lista}") #print(f"listb is {listb}")
students = [ {"sno": 101, "sname": "小张", "sgrade": 88}, {"sno": 102, "sname": "小王", "sgrade": 99}, {"sno": 103, "sname": "小李", "sgrade": 77}, {"sno": 104, "sname": "小赵", "sgrade": 66}, ] students_sort = sorted(students, key=lambda x: x["sgrade"], reverse=True) print(students) print(students_sort)
def read_file(): result = [] with open("./student_grade_input.txt") as fin: for line in fin: line = line[:-1] result.append(line.split(",")) return result def sort_grades(datas): return sorted(datas, key=lambda x: int(x[2]), reverse=True) def write_file(datas): with open("./student_grade_output.txt", "w") as fout: for data in datas: fout.write(",".join(data) + "\n") # 读取文件 datas = read_file() print("read_file datas:", datas) # 排序数据 datas = sort_grades(datas) print("sort_grades datas:", datas) # 写出文件 write_file(datas)
101,小张,88 102,小王,77 103,小李,99 104,小赵,66 105,小强,55
def compute_score(): scores = [] with open("./student_grade_input.txt") as fin: for line in fin: line = line[:-1] fields = line.split(",") scores.append(int(fields[-1])) max_score = max(scores) min_score = min(scores) avg_score = round(sum(scores) / len(scores), 2) return max_score, min_score, avg_score max_score, min_score, avg_score = compute_score() print(f"max_score={max_score}, min_score={min_score}, avg_score={avg_score}")
# key: course, value: grade list course_grades = {} with open("course_student_grade_input.txt") as fin: for line in fin: line = line[:-1] course, sno, sname, grade = line.split(",") if course not in course_grades: course_grades[course] = [] course_grades[course].append(int(grade)) print(course_grades) for course, grades in course_grades.items(): print( course, max(grades), min(grades), sum(grades) / len(grades) )
import datetime curr_datetime = datetime.datetime.now() print(curr_datetime, type(curr_datetime)) # date time to string str_time = curr_datetime.strftime("%Y-%m-%d %H:%M:%S") print("str_time", str_time) print("year", curr_datetime.year) print("month", curr_datetime.month) print("day", curr_datetime.day) print("hour", curr_datetime.hour) print("minute", curr_datetime.minute) print("second", curr_datetime.second)
import datetime birthday = "1997-12-20" birthday_date = datetime.datetime.strptime(birthday, "%Y-%m-%d") print(birthday_date, type(birthday_date)) curr_datetime = datetime.datetime.now() print(curr_datetime, type(curr_datetime)) minus_datetime = curr_datetime - birthday_date print(minus_datetime, type(minus_datetime)) print(minus_datetime.days) print(minus_datetime.days / 365)
import datetime def get_diff_days(pdate, days): pdate_obj = datetime.datetime.strptime(pdate, '%Y-%m-%d') time_gap = datetime.timedelta(days=days) pdate_result = pdate_obj - time_gap return pdate_result.strftime("%Y-%m-%d") print(get_diff_days("2021-04-28", 1)) print(get_diff_days("2021-04-28", 3)) print(get_diff_days("2021-04-28", 7)) print(get_diff_days("2021-04-01", 3))
import datetime def get_date_range(begin_date, end_date): date_list = [] while begin_date <= end_date: date_list.append(begin_date) begin_date_object = datetime.datetime.strptime(begin_date, "%Y-%m-%d") days1_timedelta = datetime.timedelta(days=1) begin_date = (begin_date_object + days1_timedelta).strftime("%Y-%m-%d") return date_list begin_date = "2021-02-28" end_date = "2021-05-03" date_list = get_date_range(begin_date, end_date) print(date_list)
import os import shutil dir = "./arrange_dir" for file in os.listdir(dir): ext = os.path.splitext(file)[1] ext = ext[1:] if not os.path.isdir(f"{dir}/{ext}"): os.mkdir(f"{dir}/{ext}") source_path = f"{dir}/{file}" target_path = f"{dir}/{ext}/{file}" shutil.move(source_path, target_path)
import os print(os.path.getsize("Beginner Guide to Python.txt")) sum_size = 0 for file in os.listdir("."): if os.path.isfile(file): sum_size += os.path.getsize(file) print("all size of dir: ", sum_size/1000)
import os # d:/workbenc/xxx search_dir = "/Users/peishuaishuai/workbench" result_files = [] for root, dirs, files in os.walk(search_dir): for file in files: if file.endswith(".txt"): file_path = f"{root}/{file}" result_files.append((file_path, os.path.getsize(file_path) / 1000)) print( sorted(result_files, key=lambda x: x[1], reverse=True)[:10] )
# -*- coding:utf-8 -*- from selenium import webdriver import time import webbrowser import re from tkinter import * from tkinter import messagebox import threading if time.time() > 1625919522: print("试用期已过") time.sleep(152222) exit() root = Tk() # 窗口名字 root.title("天猫网页监控软件") # 窗口大小 root.geometry("800x600+450+200") ftsize = 15 url = "https://gd32.tmall.com/?spm=a220o.1000855.1997427721.d4918089.7d967cb8LgqF7l" time_sleep = 60 kaishi = 0 def get_time(): return str(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) with open(f"log.log", "a+",encoding="utf-8") as goupine: goupine.write(get_time()+"软件开始运行" + "\n") kaiguan = 1 def choice7(): global kaiguan url = a_entry.get() time_sleep = int(scale.get()) with open(f"log.log", "a+", encoding="utf-8") as goupine: goupine.write(get_time()+url+"间隔时间:"+ str(time_sleep) + "\n") driver_path = r"geckodriver.exe" driver = webdriver.Firefox(executable_path=driver_path) # 浏览器首字母大写! adict = [] tupians = 0 while True: with open(f"log.log", "a+", encoding="utf-8") as goupine: goupine.write(get_time() + f"运行中" + "\n") if kaishi == 1: continue driver.get(url) # 用get方法测试 asds = driver.page_source regex = r"\.jpg" tupian = re.findall(regex, asds) if tupians: if tupians != tupian: messagebox.showinfo("图片有变化", f"图片由{tupians}张,变为{tupian}张") with open(f"log.log", "a+", encoding="utf-8") as goupine: goupine.write(get_time() + f"图片由{tupians}张,变为{tupian}张"+ "\n") lists = asds.split("\"") if adict: for i in lists: if i not in adict and "gd32.tmall.com/" in i: i = "https" + i geng_xin_str = f'<H1><a href="{i}" target="_blank">{i}</a></h1>' file_handle = open('web.html', mode='w', encoding="utf-8") file_handle.write(geng_xin_str) file_handle.close() webbrowser.open("web.html") messagebox.showinfo("网址有更新", f"具体网址请查看网页") with open(f"log.log", "a+", encoding="utf-8") as goupine: goupine.write(get_time() + f"网址有更新" + "\n") print(i) adict = lists tupians = tupian time.sleep(time_sleep) if kaiguan ==0: kaiguan =1 driver.close() exit() def choice8(): thread = threading.Thread(target=choice7) thread.start() def land(): global kaiguan kaiguan = 0 Label(root, text=f"", font=ftsize, width=5, height=8).grid(row=0, column=0) Label(root, text="监控网址:", font=ftsize, height=2).grid(row=2, column=1, sticky=E) a_entry = Entry(root, width=70) a_entry.grid(row=2, column=2, sticky=W, columnspan=4) scale = Scale(root, from_=1, to=61, orient=HORIZONTAL, tickinterval=5, resolution=1, length=400) scale.grid(row=3, column=0, columnspan=6) reset = Button(root, text="开始监控", command=choice8, font=ftsize) submit = Button(root, text="停止监控", command=land, font=ftsize) reset.grid(row=4, column=1, sticky=E) submit.grid(row=4, column=2) root.mainloop()
for i in range(100): a = 1 if i%2==0 else 3 print(a)
#-*- encoding=utf8 -*- #测试键盘和鼠标事件 from tkinter import * root = Tk();root.geometry("503x300") c1 =Canvas(root,width=200,height=200,bg="blue") c1.pack() def mouseTest(event): print(f"鼠标左键单击位置(相对于父容器):{event.x},{event.y}") print(f"鼠标左键单击位置(相对于屏幕):{event.x_root},{event.y_root}") print(f"事件绑定的组件:{event.widget}") def testDray(event): c1.create_oval(event.x,event.y,event.x+1,event.y+1) def keyboardTest(event): print(f"键盘的keycode:{event.keycode},键盘的char:{event.char},键盘的keysym:{event.keysym}") def press_a_test(event): print("press a") def release_a_test(event): print("release a") c1.bind("<Button-1>",mouseTest) c1.bind("<B1-Motion>",testDray) root.bind("<KeyPress>",keyboardTest) root.bind("<KeyPress-a>",press_a_test) root.bind("<KeyRelease-a>",release_a_test) root.mainloop()
L=[[1],[1, 1]] print(L[1]) c=input("输入层数:") print(c) cen=int(c) def triangles(L,cen): n=3 while n <= cen: for i in range(0,n-1): L.append([]) if i==0: L[n-1].append(1) L[n-1].append(1) else: L[n-1].insert(i,L[n - 2][i]+L[n - 2][i - 1]) n=n+1 return 'done' triangles(L,cen) #遍历 for i in range(cen): print(L[i])