Python中常用的功能怎么实现

其他教程   发布日期:2025年03月07日   浏览次数:214

今天小编给大家分享一下Python中常用的功能怎么实现的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大家参考一下,希望大家阅读完这篇文章后有所收获,下面我们一起来了解一下吧。

1. 新建文件夹

  1. if not os.path.exists(feature_dir):
  2. os.makedirs(feature_dir)

2. 后台运行并保存log

  1. nohup python -u test.py > test.log 2>&1 &
  2. #最后的&表示后台运行
  3. #2 输出错误信息到提示符窗口
  4. #1 表示输出信息到提示符窗口, 1前面的&注意添加, 否则还会创建一个名为1的文件
  5. #最后会把日志文件输出到test.log文件
  6. #查看
  7. tail -f test.log#如果要实时查看日志文件使用命令
  8. cat test.log#查看全部输出使用命令

3. 文件读取

  1. ###1.python
  2. #读写txt
  3. with open(r'./data/user_dict.txt','r',encoding='utf-8') as f:
  4. data = f.readlines()
  5. #追加模式
  6. with open(r'./data/user_dict.txt','a',encoding='utf-8') as f:
  7. t = '你好'
  8. f.write('
  9. '+t)
  10. #按行读取tsv / 内存大可以直接.readlines()
  11. with open('./data/train.tsv',encoding = 'utf-8') as file:
  12. line = file.readline()
  13. limit = 0
  14. while line and limit<10:
  15. print(line)
  16. limit+=1
  17. line = file.readline()
  18. ###2.json 存储dict
  19. x = {..}
  20. #save
  21. with open(r"./x.json",'w') as f:
  22. json.dump(x, f, ensure_ascii=False) #单行
  23. print('done')
  24. ## 格式化
  25. with open(r"result.json", 'w') as f:
  26. json.dump(res, f, ensure_ascii=False, indent=4)
  27. #read
  28. with open(r"./x.json",'r') as f:
  29. x = json.loads(f.readlines()[0])
  30. #读取格式化后的多行json
  31. with open(r"./x.json",'r') as f:
  32. x = json.load(f)
  33. ###3.numpy 存储list
  34. x = [x,]
  35. np.save("./././x.npy",x)
  36. x = np.load(r"./././x.npy")
  37. ###4.pandas
  38. #read xlsx
  39. data = pd.read_excel(r'xxxx.xlsx','Sheet1')
  40. #dict to df
  41. result = {x:1,y:2,..}
  42. df = pd.DataFrame(list(result.items()), columns=['key','value'])
  43. #save df
  44. df.to_csv(r"./result.csv", index=False,header=True)
  45. #read
  46. df = pd.read_csv(r'./result.csv',encoding = 'gbk')

4. 字符串判断

  1. s.islower() #判断是否所有字符小写
  2. s.isupper() #判断是否所有字符大写
  3. s.isalpha() #判断是否所有字符为字母
  4. s.isalnum() #判断是否所有字符为字母或数字
  5. s.isdigit() #判断是否所有字符为数字
  6. s.istitle() #判断是否所有字符为首字母大写

5. 统计list元素出现次数

  1. from collections import Counter
  2. x = [1,2,3,2]
  3. y= '1232'
  4. Counter(x)
  5. #>>Counter({2: 2, 1: 1, 3: 1}) #就是一个dict
  6. Counter(y)
  7. #>>Counter({'2': 2, '1': 1, '3': 1})
  8. Counter('1232')['2']
  9. #>>2

6. timestamp 转换标准时间

  1. # 把时间处理 以找到登陆时间
  2. import time
  3. def timestamp_datetime(value):
  4. format = '%Y-%m-%d %H:%M:%S'
  5. # value为传入的值为时间戳(整形),如:1332888820
  6. value = time.localtime(value)
  7. ## 经过localtime转换后变成
  8. ## time.struct_time(tm_year=2012, tm_mon=3, tm_mday=28, tm_hour=6, tm_min=53, tm_sec=40, tm_wday=2, tm_yday=88, tm_isdst=0)
  9. # 最后再经过strftime函数转换为正常日期格式。
  10. dt = time.strftime(format, value)
  11. return dt
  12. def datetime_timestamp(dt):
  13. #dt为字符串
  14. #中间过程,一般都需要将字符串转化为时间数组
  15. time.strptime(dt, '%Y-%m-%d %H:%M:%S')
  16. ## time.struct_time(tm_year=2012, tm_mon=3, tm_mday=28, tm_hour=6, tm_min=53, tm_sec=40, tm_wday=2, tm_yday=88, tm_isdst=-1)
  17. #将"2012-03-28 06:53:40"转化为时间戳
  18. s = time.mktime(time.strptime(dt, '%Y-%m-%d %H:%M:%S'))
  19. return int(s)
  20. d = datetime_timestamp('2015-03-30 16:38:20')
  21. print(d)
  22. s = timestamp_datetime(1427704700)
  23. print(s)

7. 排序

  1. #方法1.用List的成员函数sort进行排序,在本地进行排序,不返回副本
  2. #方法2.用built-in函数sorted进行排序(从2.4开始),返回副本,原始输入不变
  3. listX = [[1,4],[2,5],[3,3]]
  4. sorted(listX, key=lambda x : x[1])
  5. #>>[[3, 3], [1, 4], [2, 5]]
  6. ### 两个list按同意顺序排序
  7. list1 = [1, 2, 3, 4, 15, 6]
  8. list2 = ['a', 'b', 'c', 'd', 'e', 'f']
  9. c = list(zip(list1,list2))
  10. c.sort(reverse=True) #降序du
  11. list1[:],list2[:] = zip(*c)
  12. print(list1,list2)

8. 文件路径获取

  1. path2 = os.getcwd() #最外层执行的main.py的路径
  2. path3 = os.path.dirname(os.path.realpath(__file__)) #当前py文件的绝对路径

9. 同一行刷新打印

  1. print("
  2. ",object,end="",flush=True)
  3. #e.g.
  4. for i,img_name in enumerate(img_names):
  5. print("
  6. ",str(i)+"/"+str(len(img_names)),end="",flush=True)

10. PIL resize比opencv更清晰

  1. img = cv2.imread("000000000113_0.jpg")
  2. img = Image.fromarray(img)
  3. img = img.resize((192,192))
  4. img = np.array(img)

11. base64转opencv

  1. def imgToBase64(img_array):
  2. # 传入图片为RGB格式numpy矩阵,传出的base64也是通过RGB的编码
  3. img_array = cv2.cvtColor(img_array, cv2.COLOR_RGB2BGR) #RGB2BGR,用于cv2编码
  4. encode_image = cv2.imencode(".jpg", img_array)[1] #用cv2压缩/编码,转为一维数组
  5. byte_data = encode_image.tobytes() #转换为二进制
  6. base64_str = base64.b64encode(byte_data).decode("ascii") #转换为base64
  7. return base64_str
  8. def base64ToImg(base64_str):
  9. # 传入为RGB格式下的base64,传出为RGB格式的numpy矩阵
  10. byte_data = base64.b64decode(base64_str)#将base64转换为二进制
  11. encode_image = np.asarray(bytearray(byte_data), dtype="uint8")# 二进制转换为一维数组
  12. img_array = cv2.imdecode(encode_image, cv2.IMREAD_COLOR)# cv2解码为三通道矩阵
  13. img_array = cv2.cvtColor(img_array, cv2.COLOR_BGR2RGB)# BGR2RGB
  14. return img_array

以上就是Python中常用的功能怎么实现的详细内容,更多关于Python中常用的功能怎么实现的资料请关注九品源码其它相关文章!