Python 官方文档:入门教程 => 点击学习
1.指定一个源文件,实现copy到目标目录 个人实现: def filecopy(filename:str, cp_filename:str): ''' Author: lijl Description: 复制文
个人实现:
def filecopy(filename:str, cp_filename:str):
'''
Author: lijl
Description: 复制文件
type filename: str
type cp_filename: str
rtype: int
'''
try:
with open(cp_filename, 'w+') as f1, open(filename, 'r') as f2:
f1.write(f2.read())
except Exception as e:
print('Exception :', e)
return 1
return 0
个人实现:
def Word_count(filename:str, topN:int):
'''
Author: lijl
Description: 统计单词数量
type filename: str
type topN: int
rtype: None
'''
result = {}
table = str.maketrans('.,/\()+=:\'"', ' ')
#处理非字母字符&插入字典
with open('sample.txt', 'r') as f:
for i in f:
s = i.lower().translate(table).split()
for j in s:
if j in result.keys():
result[j] += 1
else:
result[j] = 1
#将字典按照key排序
topN_lst = sorted(result, key = lambda x:result[x], reverse=True)
for i in range(topN):
print('{}, {}'.fORMat(topN_lst[i], result[topN_lst[i]]))
return
答案参考代码:
要求用户可以排除一些单词的统计
个人实现:
def word_count(filename:str, topN:int, *args):
'''
Author: lijl
Description: 统计单词数量
type filename: str
type topN: int
type args: strs
rtype: None
'''
result = {}
table = str.maketrans('.,/\()+=:\'"', ' ')
#处理非字母字符&插入字典
with open(filename) as f:
for i in f:
s = i.lower().translate(table).split()
for word in s:
if word not in args:
result[word] = result.get(word, 0) + 1
#将字典按照key排序
topN_lst = sorted(result.items(), key = lambda result:result[1], reverse=True)
for k, v in topN_lst[:topN]:
print('{}, {}'.format(v, k))
return
答案参考代码;
个人实现:
from configparser import ConfigParser
def ini2json(filename):
'''
Author: lijl
Description: ini转json
type filename: str
rtype: str
'''
section_dict = {}
section_list = []
cfg = ConfigParser()
cfg.read(filename)
if len(cfg.items('DEFAULT')) != 0:
section_list.append('DEFAULT')
section_list += cfg.sections()
for section_name in section_list:
section_dict[section_name] = cfg.items(section_name)
return json.dumps(section_dict)
答案参考代码:
个人实现:
import os
import argparse
import datetime
from pathlib import Path
parser = argparse.ArgumentParser(add_help=False)
parser.add_argument("dir", type=str, nargs='?', default=Path.cwd())
parser.add_argument("-a","--all", action ='store_true')
parser.add_argument("-l", action ='store_true')
parser.add_argument("-h", "--human", action ='store_true')
args = parser.parse_args()
if args.dir:
dr = Path(args.dir)
MODE_DICT = {'0':'---', '1':'--x', '2':'-w-', '3':'-wx', '4':'r--', '5':'r-x', '6':'rw-', '7':'rwx'}
FILE_DICT = {'1':'-','4':'d', '2':'c', '6':'b', '3':'l', '5':'s','7':'p'}
#无参数或只有-h
if (not args.l and not args.human) or not args.l:
for i in sorted(os.listdir(dr)):
print(i, end=' ')
print()
#有-l参数
if args.l:
for i in sorted(os.listdir(dr)):
file_path = dr / i
#如果没有-a,不显示隐藏文件
if not args.all and i.startswith('.'):
continue
stat = os.lstat(file_path)
st_mode = str(oct(stat.st_mode))
mtime = datetime.datetime.fromtimestamp(stat.st_mtime).strftime('%Y-%m-%d %H:%M:%S')
#计算文件类型
new_file_kind = FILE_DICT[st_mode[2]]
#计算权限
mode=st_mode[-3:]
new_mode = ''
for m in mode:
new_mode += MODE_DICT.get(m)
#人性化显示文件大小
if args.human:
size = stat.st_size
interval = 1024
for j in ['k', 'M', 'G', 'T']:
temp_size = stat.st_size // interval
if temp_size > 0:
size = str(round(stat.st_size / interval, 1)) + j
else:
break
interval = interval ** 2
print('{}{} {:>2} {} {} {} {} {}'.format(new_file_kind, new_mode, stat.st_nlink, stat.st_uid, stat.st_gid, size if args.human else stat.st_size, mtime, i))
print()
答案参考代码:
6.匹配一个0-999之间的任意数字
个人实现:
\b[0-9]{0,3}\b
答案参考代码:
^([1-9]\d\d?|\d)(?!\d)
7.匹配合法IP地址
个人实现:
^(?:(\d|\d{2}|1\d{2}|2[0-4]\d|25[0-5])\.){3}(\d|\d{2}|1\d{2}|2[0-4]\d|25[0-5])$
答案参考代码:
(?:(\d{1,3}).){3}(\d{1,3})
可以把数据提出来后,交给IP地址解析库处理
正则的验证只是一个初步的筛选,把明显的错误过滤掉
import socket
nw = socket,inet_aton('192.168.05.001')
print(nw, socket.inet_ntoa(nw))
8.选出含有ftp的链接,且文件类型时gz或者xz的文件名
个人实现:
(?<=.*ftp.*)[^/]+(\.(?:g|x)z)$
答案参考代码:
(?<=.*ftp.*/)[^/]*\.(?:gz|xz)
--结束END--
本文标题: Python第六周 学习笔记(3)
本文链接: https://lsjlt.com/news/190979.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0