下面展示一些 内联代码片
。
一些python的小demo
#统计一篇文章中,一个单词出现的次数。
dict_english = {}
@app.route('/read_englishfileForwords')
def read_englishfileForwords():
with open("./input_english.txt") as fin:
for line in fin :
line = line[:-1] #去末尾/n
words = line.split()
for word in words:
if word not in dict_english :
dict_english[word] = 0
dict_english[word] +=1
print(dict_english)
#计算文件大小和
import os
def fileSize():
sum_size = 0
print(os.path.getsize("./input_english.txt"))
for file in os.listdir("."): #不需os.path.listdir
sum_size += os.path.getsize(file)
print(sum_size/1000)
fileSize() # 1.2kb 1262
# 按照文件后缀整理文件
import os
import shutil
print(os.path.splitext("./input_english.txt"))
flie_list = []
for file in os.listdir("."):#当前目录
ext = os.path.splitext(file)[1] #元组
ext = ext[1:]
if not os.path.isdir(f"./dir1/{ext}"):
os.mkdir(f"./dir1/{ext}")
souce_path = f"./{file}"
target_path =f"./{ext}/{file}"
shutil.copy(souce_path,target_path)
import os
# 递归目录找出最大的文件
result_files = []
search_dir = "D:\\Game"
def funcFilesMax():
for root , dirs , files in os.walk(search_dir): #root :当前目录 dirs :当前目录子目录 files :文件
for file in files:
file_path = f"{root}/{file}"
result_files.append((file_path,os.path.getsize(file_path)/1024))
print(result_files)
result_files_sort = sorted(result_files,key=lambda x :x[1]) # key=lambda x :x[1] 够我学一辈子
print(result_files_sort)
funcFilesMax()
grade_dict = {}
list_grade =[]
tmp = 0
def funcGradeMax():#自己写的旧方法
with open("./input_grade_sort.txt",encoding='utf-8') as fin :
for line in fin :
line = line[:-1]
grades = line.split(",")
list_grade.append(grades)
print(list_grade)
for grade in list_grade :
if grade[0] not in grade_dict :
grade_dict[grade[0]] = int(grade[3])
tmp = int(grade[3])
if int(grade[3]) > tmp :
grade_dict[grade[0]] = int(grade[3])
tmp = int(grade[3])
print(grade_dict) #最后做到的效果是,生成一个字典,科目对应最大的分数
def funcGradeMaxNew():
with open("./input_grade_sort.txt",encoding='utf-8') as fin :
for line in fin :
line = line[:-1]
course,sno, sname,grade = line.split(",")
if course not in grade_dict :
grade_dict[course] = []
grade_dict[course].append(int(grade))
# print(grade_dict)
for course, grades in grade_dict.items():
print(course,max(grades),min(grades),sum(grades)/len(grades))
funcGradeMaxNew()
#关联两个文件
class ReadTeacher():
#初始化方法
def __init__(self ,name , age):
self.name = name
self.age = age
#读取方法
def readTeacherKeyValues(self):
dict_teacher = {}
with open("./teacher.txt",encoding='utf-8') as fin :
for line in fin :
line = line[:-1]
cource ,name = line.split(",")
if cource not in dict_teacher :
dict_teacher[cource] = name
return dict_teacher
#关联方法
def relevancyTxt(self):
list_stus = []
dic = self.readTeacherKeyValues()
with open("./input_grade_sort.txt",encoding='utf-8') as fin :
for line in fin:
line = line[:-1]
stu = line.split(",")
list_stus.append(stu)
# print(list_stus)
for stu in list_stus:
for k ,v in dic.items():
if stu[0] == k :
stu.append(v)
return list_stus
# 写入文件中
def writeFile(self):
list_result = self.relevancyTxt()
print(list_result)
with open("./output_studentandteacher.txt","w") as fin:
for messages in list_result :
fin.write(",".join(messages)+"\n")
if __name__ == '__main__':
read = ReadTeacher("h老师",18)
read.writeFile()
# 合并多个txt文件
import os
dir_path = "./dir1"
content = []
for file in os.listdir(dir_path):
file_path = f"{dir_path}/{file}"
if os.path.isfile(file_path) and file.endswith(".txt"):
with open(file_path) as fin :
for line in fin:
content.append(line)
print(content)# 等到三个文件的数据,放在一个列表。 那么接下来要做的的就是,将列表的数据放在一个统一的的文件中。
# if not os.path.isfile(f"{dir_path}/output_write.txt"):
# os.makefile(f"{dir_path}/output_write.txt")
with open("./dir1/output_write.txt" ,"w") as fin : #不存在就创建
for con in content :
fin.write(con)
#去重
def listquchongTest(list1):
set1 = set()
for i in list1 :
set1.add(i)
list2 = []
for j in set1:
list2.append(j)
return list2
print(f"经过去重后,列表为:{listquchongTest([1,2,3,3,4,4,5,5,6,6,6,1,7,8,9,9,10])}")