Python Ecosystem之Python篇章三

高亮颜色说明:突出重点
个人觉得,:待核准个人观点是否有误

本篇博客涵盖以下内容:

  • 文件和异常
  • 测试代码
  • Python算法与数据结构
  • Python项目实践

编写深度学习项目实验的代码时, 合理的脚本文件组织结构

Python代码阅读

  代码阅读 要想快速了解一个.py脚本文件的功能与作用,可以先从def main()方法开始看,看main()中调用了哪些方法和建立了哪些类对象;然后去看下这些方法和类的API文档注释(docstrings);此外,还可以关注下main()print('提示')中的一些提示;以及整个脚本文件中的description字段;

Python代码调试

  代码调试 关于代码测试:了解一些基本的测试知识,做一些基本的单元测试、功能测试、边界测试以及异常测试。

import os

print(os.getcwd())  # 返回当前工作目录

Python 输出 log 日志

Python库

  查看 Python 包的路径:import tensorboard print(tensorboard.__file__)

pip install 命令

  pip是python环境的包管理工具,用它可以方便地管理第三方包,其功能类似于Linux系统下的yum或apt-get。

Python处理文件

  • os.sep, 路径中的分隔符
    python中如何兼容 windows 和 linux 不同环境的操作系统路径_小土豆小洋芋的博客-CSDN博客 20220905
  • Pathlib module in Python
    代码: anaconda3/envs/my_gpu_py3/lib/python3.8/pathlib.py
    pathlib — Object-oriented filesystem paths — Python 3.10.2 documentation
  • 获取文件路径和文件名,用于后面的存储
    path_to_file = './data/images/val2017/1 (1).jpg'
    
    # 方式一
    filedir = "/".join(path_to_file.split("/")[:-1])  # 获取文件路径
    filename = path_to_file.split("/")[-1]  # 获取文件名
    
    # 方式二
    from pathlib import Path
    path_to_file_ = Path(path_to_file)
    filedir_ = path_to_file_.parents[0]  # <class 'pathlib.Path'>
    filename = path_to_file_.name  # <class 'str'>
    filename_wo_suffix = path_to_file_.stem  # <class 'str'>
    
    
  • os.path.basename()
    # Returns the final component of a pathname
    basename = os.path.basename(dic["file_name"])
    
    # 例如,dic["file_name"]='/media/data/images/val2017/1 (1).jpg'
    # 则basename = '1 (1).jpg'
    

移动文件文件夹

glog.glob(), 遍历文件

glob.glob(str(p / '**' / '*.*'), recursive=True)
glob.glob(str(p / '*.*'), recursive=True)

Python 读写txt

Python 存储数据的方式及耗时对比

json.dumps()报错TypeError: Object of type float32 is not JSON serializable

20200906记:

import mmcv.fileio as mmcvfileio  # C:/Users/lu/.PyCharm2019.2/system/remote_sources/-1468910861/-416239508/mmcv/fileio/io.py
mmcvfileio.dump(some_data, f'{path_to_recorddata}/some_data.json')

# ---------------------------分割线---------------------------
C:/Users/usrname/.PyCharm2019.2/system/remote_sources/-1468910861/-416239508/mmcv/fileio/handlers/json_handler.py
# Copyright (c) Open-MMLab. All rights reserved.
import json

from .base import BaseFileHandler


class JsonHandler(BaseFileHandler):

    def load_from_fileobj(self, file):
        return json.load(file)

    def dump_to_fileobj(self, obj, file, **kwargs):
        json.dump(obj, file, **kwargs)

    def dump_to_str(self, obj, **kwargs):
        return json.dumps(obj, **kwargs)
# ---------------------------分割线---------------------------

You are here because when you try to dump or encode Python set into JSON, you received an error, TypeError: Object of type set is not JSON serializable.

The built-in json module of Python can only handle Python primitives types that have a direct JSON equivalent. i.e., The fundamental problem is that the JSON encoder json.dump() and json.dumps() only knows how to serialize the basic types by default (e.g., dictionary, lists, strings, numbers, None, etc.). To solve this, we need to build a custom encoder to make set JSON serializable.
(待阅读) ***Python JSON Serialize Set 20200609

Python json dump(s) to Encode dict into JSON | Write JSON in file 20200609
Serialize and Deserialize complex JSON in Python | by Yuchen Zhong | Medium 20190114
在使用json.dumps时遇到报错TypeError: Object of type float32 is not JSON serializable_gqixf的博客-CSDN博客20180102

Big-O Efficiency of Python List Operators

Table 2: Big-O Efficiency of Python List Operators
OperationBig-O Efficiency
index []O(1)
index assignmentO(1)
appendO(1)
pop()O(1)
pop(i)O(n)
insert(i,item)O(n)
del operatorO(n)
iterationO(n)
contains (in)O(n)
get slice [x:y]O(k)
del sliceO(n)
set sliceO(n+k)
reverseO(n)
concatenateO(k)
sortO(n log n)
multiplyO(nk)
*** 3.6. Lists — Problem Solving with Algorithms and Data Structures
Python自带数据结构的运行效率_勇气与行动-CSDN博客 20170603
*** Big O Notation and Algorithm Analysis with Python Examples
All You Need to Know About Big O Notation [Python Examples] 20191008
python数据结构效率问题_qq_32796425的博客-CSDN博客 20170330

Python爬虫

Python爬虫爬取图片

看黑客是怎么爬取百度图片(动态页面) 20210125
https://mp.weixin.qq.com/s/xNTqBC-LYPiGHhcxhM54pA
python爬取“百度小姐姐” 20200523
https://mp.weixin.qq.com/s/hLShPVqigs7dgYGrfYdYFg
Python爬虫 | 批量爬取某图网站高质量小姐姐照片 20210119
https://mp.weixin.qq.com/s/QkboNzs-wrYWwuH7KSfY6A

Python爬虫爬取电影榜单上的电影信息

20210806记:
Learn_Spider_002.py

Python list 和 numpy 实现 3-sigma 异常值剔除和异常值替换实例

问题记录

问题描述
  开始
原因分析:
  开始
解决方案:
  开始

“SyntaxError: invalid syntax”

问题描述
  Python运行程序报错"SyntaxError: invalid syntax";
原因分析:

  • 粗心问题
    忘记在 if , elif , else , for , while , class , def 末尾添加 冒号(😃; 误将 = 当成 == 使用; (), [] 等符号没有成对使用;
  • 版本问题
    因为python2和python3是不兼容的, 所以一些可以在python2上运行的代码不一定可以在python3上运行, 可以尝试更换版本;
  • 路径问题
    记得仔细查看自己的路径是否正确;

debug in VS Code, 无法 step into

问题描述
  debug in VS Code, 无法 step into, 提示如下问题,

Could not load source '<__array_function__ internals>': Source unavailable.

原因分析and解决方案:
  在launch.json中配置"justMyCode": false即可,

# .vscode\launch.json
{
    ...,
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Python: Current File",
            "type": "python",
            "request": "launch",
            "program": "${file}",
            "console": "integratedTerminal",
            "justMyCode": false
        }
    ]
}

VS Code - Python Debugging - Step into internal functions - Stack Overflow 20220721

二级标题

  

待补充

  

待补充

  



文字居中

数学公式粗体 \textbf{} 或者 m e m o r y {\bf memory} memory
数学公式粗斜体 \bm{}

摘录自“bookname_author”
此文系转载,原文链接:名称 20200505

高亮颜色说明:突出重点
个人觉得,:待核准个人观点是否有误

分割线

分割线


我是颜色为00ffff的字体
我是字号为2的字体
我是颜色为00ffff, 字号为2的字体
我是字体类型为微软雅黑, 颜色为00ffff, 字号为2的字体

分割线

分割线
##问题记录
问题描述
  开始
原因分析:
  开始
解决方案:
  开始

Markdown表格

方法命令备注
内容内容内容
内容内容内容

为长文本指定列宽实现换行

xxx
| xxx | xxx xxx |
very very very long long long text
| xxx
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值