呕心沥血整理的30个Python代码实现的常用功能

it2024-11-24  15

python 3.7,呕心沥血整理的30个Python代码实现的常用功能

涉及到的常用功能: 字符串相关操作 列表相关操作 生成日历,判断闰年 IO操作 基础数学计算 冒泡排序 turtle画五角星

#1,字符串大小写转换

str_random = 'you can DO whatever you want to DO with python' print(str_random.title()) #每个单词的第一个字母大写 print(str_random.capitalize()) #只转换第一个字母为大写 print(str_random.lower()) #所有字母转换成小写 print(str_random.upper()) #所有字母转换成大写

#2,判断字符串的类型(可以自己写 test case)

print('test case 1') str_random = 'python3.7/Java/C++' print(str_random.islower()) #判断字符是否都是小写 print(str_random.isupper()) #判断字符是否是都大写 print(str_random.istitle()) #判断字符是否是标题大写 print(str_random.isspace()) #判断字符是否都是空白字符,\n\t\r print(str_random.isalnum()) #判断字符是否都是数字或者字母 print(str_random.isalpha()) #判断字符是否是都是字母 print(str_random.isdigit()) #判断字符是否是都是数字

#3,计算任意月份的天数

import calendar year = int(input('please enter the year: ')) month = int(input('please enter the month: ')) DaysofMonth = calendar.monthrange(year, month) print('%s year %s month has %s (weekday, days)' % (year, month, DaysofMonth)) #weekady是这个month的第一天的工作日,比如input的是2020年10月,(weekday, days)=(3,31)即10月1日是星期四,本月有31天。

#4,获取前天,昨天,今天的日期

import datetime today = datetime.date.today() oneday = datetime.timedelta(days = 1) yesterday = today - oneday thedaybeforeyesterday = today - 2 * oneday print(thedaybeforeyesterday, '\n', yesterday, '\n', today)

#5,生成日历

import calendar year = int(input('please enter the year: ')) month = int(input('please enter the month: ')) print(calendar.month(year, month)) #输出当月的日历 print(calendar.calendar(year)) #输出整年的日历

#6,判断是否是闰年

year = int(input('please enter the year: ')) if (year % 4) == 0 and (year % 100) != 0 or (year % 400) == 0: print('%s is leap year' % (year)) else: print('%s is NOT leap year' % (year))

#7,文件IO操作

with open('test.txt', 'wt') as out_txt: #写入内容 out_txt.write('this text will be written into file \n you can see me now.') with open('test.txt', 'rt') as in_txt: #读取内容 content = in_txt.read() print(content)

#8,输出指定文件的路径,以.mp3为例

import os path = r'C:\Users\python_music download' musicpathlist = [] for root, dirs, files in os.walk(path): #root为文件夹的名字, dirs为文件夹下子文件夹集合, files为文件夹中的文件集合 for file in files: if os.path.splitext(file)[1] == '.mp3': #判断是否是mp3文件 musicpathlist.append(os.path.join(path, file)) #生成列表 print(musicpathlist)

#9,输出某个路径下的所有子文件夹路径

import os filepath = r'C:\python test\test_202009' for i in os.listdir(filepath): subfilepath = (os.path.join(filepath, i)) #文件夹下的所有目录,包含子文件夹目录 if os.path.isdir(subfilepath): #只输出是子文件夹的目录 print(subfilepath)

#10, 正则匹配,以51job为例

import re file = open('51job.txt', encoding='UTF-8') #搜索后F12检查源代码,copy tag的内容到txt中,也可以用request模块 contents = str(file.readlines()) #读取内容 pattern_tag1 = re.compile(r'{"type":.*?"tags":.*?"job_name":"(.*?)".*?"adid":""}', re.S) #匹配工作title pattern_tag2 = re.compile(r'{"type":.*?"tags":.*?"company_name":"(.*?)".*?"adid":""}', re.S) #匹配公司名 pattern_tag3 = re.compile(r'{"type":.*?"tags":.*?"providesalary_text":"(.*?)".*?"adid":""}', re.S) #匹配薪资 pattern_tag4 = re.compile(r'{"type":.*?"tags":.*?"workarea_text":"(.*?)".*?"adid":""}', re.S) #匹配工作地点 pattern_tag5 = re.compile(r'{"type":.*?"tags":.*?"updatedate":"(.*?)".*?"adid":""}', re.S) #匹配发布日期 tag1_list = re.findall(pattern_tag1, contents) #以列表形式存储各项内容 tag2_list = re.findall(pattern_tag2, contents) tag3_list = re.findall(pattern_tag3, contents) tag4_list = re.findall(pattern_tag4, contents) tag5_list = re.findall(pattern_tag5, contents) print(tag1_list, len(tag1_list)) #输出并检查 print(tag2_list, len(tag2_list)) print(tag3_list, len(tag3_list)) print(tag4_list, len(tag4_list)) print(tag5_list, len(tag5_list)) #以上5类信息(也可增加匹配其他信息)可以整合在同一个列表中 file.close()

#11,简单操作excel,以例10匹配的5类信息的内容为例

import xlwt file1 = xlwt.Workbook() sheet = file1.add_sheet('job_info') #创建工作表 row0 = ["序号","职位名","公司名","工作地点","薪资","发布时间"] #第一行内容 for i in range(0, len(row0)): sheet.write(0, i, row0[i]) #第一行内容写入 for j in range(0, len(tag1_list)): sheet.write(j+1, 0, j+1) #第一列序号内容写入 sheet.write(j+1, 1, tag1_list[j]) #第二列job_name内容写入 sheet.write(j+1, 2, tag2_list[j]) #第三列company_name内容写入 sheet.write(j+1, 3, tag3_list[j]) #第四列providesalary_text内容写入 sheet.write(j+1, 4, tag4_list[j]) #第五列workarea_text内容写入 sheet.write(j+1, 5, tag5_list[j]) #第六列updatedate内容写入 file1.save('test_51job.xls') #保存

#12,十进制转换成二进制,八进制,十六进制

num = int(input('please enter a number: ')) print('decimal number is:', num) print('binary number is:', bin(num)) print('octonary number is:', oct(num)) print('hexadecimal number is:', hex(num))

#13,求两个数的最大公约数

x = int(input('please enter a number: ')) y = int(input('please enter another number: ')) def gcd(a, b): if a < b: a, b = b, a while b != 0: temp = a % b a, b = b, temp return a print('the greatest common divisor of %s and %s is %s' % (x, y, gcd(x, y)))

#14,求两个数的最小公倍数

x = int(input('please enter a number: ')) y = int(input('please enter another number: ')) bigger = max(x, y) smaller = min(x, y) for i in range(1, smaller + 1): if bigger * i % smaller == 0: print('the least common multiple of %s and %s is %s' % (x, y, bigger * i)) break

#15,生成斐波那契数列

n = int(input('please enter a number: ')) def fib(n): if n == 1: return [1] if n == 2: return [1, 1] fib = [1, 1] for i in range(2, n): fib.append(fib[-1] + fib[-2]) return fib print(fib(n))

#16,获取最大值和最小值

numbers = list(map(int, input('please enter the numbers and split with space:').split())) print('the max number is %s' % (max(numbers))) print('the min number is %s' % (min(numbers)))

#17,判断奇数和偶数

numbers = list(map(int, input('please enter the numbers and split with space:').split())) for i in range(len(numbers)): if numbers[i] % 2 == 0: print('%s is an even number.' % numbers[i]) else: print('%s is an odd number.' % numbers[i])

#18,计算x的平方根和立方根

x = float(input('please enter a number x = ')) print('x square root is %.5f' % (x ** (1 / 2))) print('x cube root is %.5f' % (x ** (1 / 3)))

#19,输出9*9乘法表,

for i in range(1, 10): for j in range(1, i + 1): print('%d * %d = %d' ', ' % (i, j, i * j), end = '') print('\n')

#20,计算阶乘n!

n = int(input('please enter a number: ')) Factorial = n for i in range(1, n): Factorial *= i print('%s! = %s' % (n, Factorial))

#21,计算a的平方+b的平方+c的平方+…

array = list(map(int, input('please enter the numbers and split with space:').split())) sum_array = 0 for i in range(len(array)): sum_array += array[i] * array[i] print(sum_array)

#22,计算x的n次方

x = float(input('please enter x = ')) n = int(input('please enter n = ')) print('the %sth power of %.2f is %.2f' % (n, x, x ** n))

#23,list中的字符大小写转换

list_name = ['Tom', 'Robert', 'Jimmt', 'Lucy', 'Aaron', 'Jack', 'Peter'] print([i.capitalize() for i in list_name]) print([i.upper() for i in list_name]) print([i.lower() for i in list_name])

#24,字典key和value对换位置产生新字典

dict_x = {'Jan': '1', 'Feb' : '2', 'Mar' : '3', 'Apr' : '4'} print(dict_x) dict_y = {b : a for a, b in dict_x.items()} print(dict_y)

#25,逐个输出列表中的每个元素

list_name = ['Tom', 'Robert', 'Jimmt', 'Lucy', 'Aaron', 'Jack', 'Peter'] for i in range(len(list_name)): print('%s is getting rich!' % (list_name[i]))

#26, 逐个打印列表中每个元素的字符

list_com = ['writing', 'encourage', 'you', 'enroll', 'advantage', 'course'] for i in range(len(list_com)): for j in range(len(list_com[i])): print(list_com[i][j], end = ' ')

#27,合并列表并去除重复元素

list_a = [456,867,132,7,465,1,9,563,4] list_b = [546,465,456,45,123,1,54,867,8,7] print(list_a + list_b) #两个列表重新组合,有重复 print(set(list_a + list_b)) #两个列表重新组合,无序,没有重复,输出的是集合 print(list(set(list_a + list_b))) #两个列表重新组合,无序,没有重复,输出的是列表 print(sorted(list(set(list_a + list_b)))) #两个列表重新组合,有序,没有重复,输出的是列表

#28,随机生成验证码,可以取消循环

import random, string count = 0 while True: num_random = '0123456789' str_random = string.ascii_letters ver_code = random.sample(num_random + str_random, 6) ver_code = ''.join(ver_code) print(ver_code) count += 1 if count >= 10: break

#29,冒泡排序

list_random = [456,15,48,9,6,41,8,59,4,498,94,84,96,56,554,56,114,564,45,64] def BubbleSort(): for i in range(len(list_random) - 1): for j in range(len(list_random) - 1 - i): if list_random[j] > list_random[j + 1]: list_random[j], list_random[j + 1] = list_random[j + 1], list_random[j] return list_random print(BubbleSort())

#30, turtle画五角星

import turtle turtle.pensize(15) turtle.pencolor('yellow') turtle.speed(3) turtle.fillcolor('red') turtle.hideturtle() turtle.begin_fill() for _ in range(5): turtle.forward(200) turtle.right(144) turtle.end_fill() turtle.penup() turtle.goto(-20,-180) turtle.color('violet') turtle.write('Five-pointed Star', font=('Arial', 25, 'normal')) turtle.mainloop()

感谢大家看到这里,如上述例子有出入,还望指正,十分感谢!

最新回复(0)