程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python introductory learning exercise

編輯:Python

Study Python Must brush 100 A classic exercise , Not practicing is learning in vain !!!_ Bili, Bili _bilibili

The hand tapping code is as follows :

# Column de duplication
from pickletools import read_uint1
def ss(lis):
r=[]
for i in lis:
if i not in r:
r.append(i)
return r
li=[3,22,2,22,1]
sdsad=[33,22,1,44]
print(li,ss(li))
print(sorted(sdsad))# Yes list Sort
# Dictionaries Tuple sorting
dict_shh=[{'score':1,'score':3,'score':2}]
sor=sorted(dict_shh,key=lambda x:x['score'])
# Read TXT file , And put \n Remove the newline character , And sort by a certain value
def read_file():
res=[]
with open("./rr.txt") as fin:
for line in fin:
line=line[:-1]# End \n Remove the newline character
res.append(line,split(","))# The data interval is , Get rid of “,”
return res
def sort_g(datas):
return sorted(datas,key=lambda x: int(x[2]))
def write_f(datas):
with open ("./rrinput.txt","w") as fount:
for data in datas:
fount.write(",".join(data)+"\n")
# Output three values at the same time
def com_score():
scor=[]
with open("./rr.txt") as fin:
for line in fin:
line=line[:-1]# End \n Remove the newline character
fields=line.split(",")
scor.append(int(fields[-1]))# Take the last one , And put str Convert to int
maxS=max(scor)
mins=min(scor)
avs=round(sum(scor)/len(scor),2)
return maxS,mins,avs
# Count the number of words that appear most in English words
# Method 1
def mostString():
dict = {}
fr = open('preprocessing.txt')
k = 0
n = 0
for line in fr.readlines():
for s in line.strip().split(' '):
if s not in dict.keys():
dict[s] = 0
else:
dict[s] = dict[s] + 1
if dict[s]>=n:
k = s
n = dict[s]
#print(dict)
print(k)
Method 2
word_count={}
with open("./untitled.txt") as fin:
for line in fin:
line=line[:-1]# End \n Remove the newline character
words=line.split()
for word in words:
if word not in word_count:
word_count[word]=0
word_count[word]+=1
tt=sorted(word_count.items(),key=lambda x:x[1],reverse= True)[:10]
print(tt)
# Read the files in the folder
from importlib.resources import contents
import os
import shtuli
dir="./sss"
sum_size=0
for file in os.listdir(dir):
if os.path.isfile(file):
sum_size+=os.path.getsize(file)# Find the file size
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}"
# Recursively search the directory , Find the largest file
import os
# d:/workbenc/xxxsearch_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))
sorted(result_files,key=lambda x: x[1],reverse=True)[:10]
# The highest and lowest average scores of each class
def compute_quanbanscore():# Read the file for calculation
course_grades=[]
with open("./student_grade_input",encoding="utf-8") as fin:# Read the file , If the encoding method is not set, the code will be garbled
fin.readlines()
for line in fin:# Read every line
line=line[:-1]# This syntax is to remove the last line break
course,sno,sname,grade=line.split(",")
if course not in course_grades:
course_grades[course ]=[]
course_grades[course].append(grade)
for course,grades in course_grades.items():
print(
course,
max(grade) ,
min(grade) ,
sum(grade) /len(grade)
)
# Implement different file associations
course_tech_map={}
with open("./student_grade_input",encoding="utf-8") as fin:# Read the file , If the encoding method is not set, the code will be garbled
for line in fin:# Read every line
line=line[:-1]# This syntax is to remove the last line break
course,teacher=line.split(",")
course_tech_map[course ]=teacher
with open("./student_grade_input")as fin:
for line in fin:# Read every line
line=line[:-1]# This syntax is to remove the last line break
course,sno,sname,sgrade=line.split(",")
teacher=course_tech_map.get(course)
print(course,teacher,sno,sname,sgrade)
# Achieve batch TXT File merge
import os
datadir="./ssss/sss"
contents=[]
for file in os.listdir(datadir):
file_path=f"{datadir}/{file}"
if os.path.isfile(file_path) and file.endswith(".txt"):
print(file_path)
with open(file_path)as fin:
contents.append(fin.read())
final_context="\n".join(contents)
with open("./a/a.txt","w") as fout:
fout.write(final_context)
# Count the number of people in each interest
like_coun={}
with open("./like.txt",encoding="utf-8") as fin:
for line in fin:
line=line[:-1]
sna,likes=line.split(",")
likelist=likes.split(",")
for like in likelist:
like_coun[like]=0
like_coun[like]+=1
print(like_coun)
# # Get the current date and time
from ast import pattern
import datetime
curr_datetime=datetime.datetime.now()
str_time=curr_datetime.strftime("%Y-%m-%d %H:%M:%S")
curr_datetime.year
curr_datetime.month
curr_datetime.day
curr_datetime.hour
curr_datetime.minute
curr_datetime.second
# Count your age
birthday="2022-01-02"
birthday_date=datetime.datetime.strptime(birthday,"%Y-%m-%d")
minus=curr_datetime-birthday_date
sui=minus/365
# Calculate the date a few days before any date
def get_days(pdate,days):
pdate_obj=datetime.datetime.strptime(pdate,"%Y-%m-%d")
time_gap=datetime.timedelta(days=days)
pdate_r=pdate_obj-time_gap
return pdate_r.strftime("%Y-%m-%d")
import datetime
from traceback import print_tb
from unittest import result
def getdate_range(bdate,edate):
datelist=[]
while bdate<=edate:
datelist.append(bdate)
bdate_obj=datetime.datetime.strptime(bdate,"%Y-%m-%d")
days_timedelta=datetime.timedelta(days=1)
bdate=(bdate_obj+days_timedelta).strftime("%Y-%m-%d")
return datelist
print(getdate_range("2022-01-05","2022-02-05"))
#unix Time stamp to date
unix_time=1620747647
datetime_obj=datetime.datetime.fromtimestamp(unix_time)
datetime_str=datetime_obj.strftime("%Y-%m-%d %H:%M:%S")
# Calculation date week on week
date_sale={}
is_first_line=True
with open("./like.txt",encoding="utf-8") as fin:
for line in fin:
if is_first_line:
is_first_line=False
continue
line=line[:-1]
date,salenum=line.split("\t")
date_sale[date]=float(salenum)
def get_days111(pdate,days):
currtime=datetime.datetime.strptime(pdate,"%Y-%m-%d")
timedelta1=datetime.timedelta(days=-days)
(currtime+timedelta1).strftime("%Y-%m-%d")
for date,salenum in date_sale.items():
date7=get_days111(date,7)
sale_num7=date_sale.get(date7,0)
if sale_num7==0:
print(date,salenum,0)
else:
weekdiff=(salenum-sale_num7)/sale_num7
print(date,salenum,sale_num7,weekdiff)
# Regular expressions Specific date
import re
def date_is_right(date):
return re.match("\d{4}-\d{2}-\d{2}",date) is not None
date1="2020-05-20"
date2="202-06-01"
date_is_right(date1)
date_is_right(date2)
# Regular expression phone number
content="aadasd18888888888da;lskd;alkf1231231njdnfuisf15422222222"
pattern=r"1[3-9]\d{9}"
re.sub(pattern,r"\1*************",content)# The mobile phone number is mosaic
results=re.findall(pattern,content)
for result in results:
print(result)
file_cont=""
with open("./like.txt",encoding="utf-8") as fin:
file_cont=fin.read()
results=re.findall(pattern,file_cont)
# Regular expression mailbox
pattern2=re.compile(r"""
[a-zA-Z0-9_-]+
@
[a-zA-Z0-9]+
\.a
[a-zA-Z]{2,4}
""",re.VERBOSE)
results1=pattern2.findall(content)
# Regular expressions Check the password
def check_mima(ps):
if not 6<=len(ps)<=20:
return False," stay 6-20 Between "
if not re.findall(r"[a-z]",ps):
return False," Less a-z"
if not re.findall(r"[A-Z]",ps):
return False," Less A-Z"
if not re.findall(r"[0-9]",ps):
return False," Less numbers "
if not re.findall(r"[^0-9a-zA-Z]",ps):
return False," Less special symbols "
# Regular expressions Fixed extraction
txtxt=""" bought 1 Five kilos of cucumber flowers 8 element
bought 2 Five kilos of peanuts were spent 7.5 element """
for line in txtxt.split("\n"):
pattern3=r"\d Jin .* It took \d+(\.\d+)? element "# first place \d Numbers ,.* Any character ,\d Numbers +(\.\d+)? escape . The following numbers are optional ,+ One or more
pattern4=r"(\d) Jin (.*) It took (\d+(\.\d+)?) element "#() grouping
match=re.search(pattern4,line)
if match:
print(f"{match.group(1)}\t{match.group(2)}\t{match.group(3)}")
# Regular expressions Uniform date format
cont="""2012/06/01,2014.05.06,05-28-2020,5/29/2022"""
con=re.sub(r"(\d{4})/(\d{2})/(\d{2})",r"\1-\2-\3",cont)
con=re.sub(r"(\d{4})\.(\d{2})\.(\d{2})",r"\1-\2-\3",cont)
con=re.sub(r"(\d{2})-(\d{2})-(\d{2})",r"\3-\1-\2",cont)
con=re.sub(r"(\d{1})/(\d{2})/(\d{2})",r"\3-0\1-\2",cont)
# English word participle
words=re.split(r"[\s.()-?]+,",cont)#\s A series of special symbols such as spaces
import pandas as pd
pd.Series(words).value_counts()[:20]# The first twenty
# Chinese word segmentation
comzn=""" Li Ming tells Hanmeimei , North Country scene , Thousands of miles of ice , Thousands of miles of snow .
Look inside and outside the Great Wall , But I was reckless ; Up and down the river , Suddenly lost .
Dancing silver snake among snowing mountains , The original chi wax , I want to compete with God .
It must be sunny , Look at the red dress , grow more enchanting .
the country is so rich in beauty , Many heroes have been invited to bow down .
Cherish the Qin emperor and Hanwu , Lose a little bit of literary talent ; Tang Zong, Song Zu , A little less coquettish ."""
comzn1=re.sub(r"[\s.,、]",comzn)
import jieba
word_list=jieba.cut(comzn)
# The person's name
import jieba.posseg as posseg
for word,flag in posseg.cut(comzn):
if flag=="nr":
print(word,flag)


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved