python编程问题--第四次

该博客记录了Python编程中的诸多问题与技巧,包括程序结果异常排查、变量判定、循环使用、加密方法、异常处理、模块调用等,还涉及字典操作、字符串处理、进程管理等内容,同时分享了一些工具和代码规范相关的知识。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

20220811

程序执行无报错信息,但结果不对,很有可能是
try,catch的原因,没把报错信息打印出来,或者
scrapy没有打开调试功能输出

20220721

python判定是否为none
直接
if xx :就可以,相当于 if True:

20220630


【Python】AttributeError: Can‘t get attribute ‘Vocab‘ on <module ‘gensim.models.word2vec‘ from
https://blog.csdn.net/ztf312/article/details/120841163

20220612

在这里插入图片描述https://www.bilibili.com/video/BV1S4411X7nF?spm_id_from=333.337.search-card.all.click
property
在这里插入图片描述assert

20220608

在这里插入图片描述星号的作用,把列表展开

python看不到源码,说明不是python代码写的
在这里插入图片描述
传参如果只传一个参数,其会赋值给没有默认值的第一个参数

networks.__dict__
networks如果是文件夹,那输出结果为文件夹内的模块名称和其他一些属性


```python
 callable(networks.__dict__[name])
 对象是否是可以调用的

20220526

https://baijiahao.baidu.com/s?id=1724971863146590785&wfr=spider&for=pc
zfill(5) :填充为指定长度的字符串

python argparse
metevar :参数的别名?

```python
  parser.add_argument('--models', '-m', metavar='NACHINE', default='slbr')
  -m 是缩写

20220517

    name都是完整路径的name,不仅仅是文件的名称
    os.rename(oldname,newname)
    更改名称

until 循环
until 循环执行一系列命令直至条件为 true 时停止。
until 循环与 while 循环在处理方式上刚好相反。
一般 while 循环优于 until 循环,但在某些时候—也只是极少数情况下,until 循环更加有用。

20220425

https://www.cnblogs.com/shukeshu/p/14741696.html
python,md5加密

20220317

https://www.cnblogs.com/Lival/p/6203111.html
raise发明一个异常

20220228

 orderedItem = [v[0] for v in sorted(localD.items(), key=lambda p:(p[1],-ord(p[0])), reverse=True)]
 python字典排序先按value排序,value相同的时候按可以排序
 reverse是从大到小排序

20220226

SyntaxError: Non-UTF-8 code starting with ‘\xbd’ in file
https://blog.csdn.net/cute_boy_/article/details/101262529

20220224

https://blog.csdn.net/qq_41320433/article/details/104299812

解决报错Process finished with exit code -1073741571 (0xC00000FD),修改栈大小

迭代器,迭代函数要运行需要通过for循环的形式
https://www.runoob.com/python3/python-merging-two-dictionaries.html
字典合并合并字典

20220218

Python 将字符串作为代码执行
exec

https://blog.csdn.net/qq_43201127/article/details/111501907
https://www.zhihu.com/question/37720196
中英文标点符号转换

    # 剔除掉specification为空值的
    null_type = ['nan', None, '']
    for i_type in null_type:
        data = data.loc[data['specifications'] != i_type,:]
    data.loc[data['specifications'].notnull(),:]
    
    全部处理完之后再做空值筛选?或者处理前后都需要

20220127

RuntimeError: An attempt has been made to start a new process before the current pr
多进程需要在main函数中运行

20220121

一个函数中有多个return只要执行了其中一个,剩下的return都不会执行

20220117

create_Var = locals()
for i in range(data_divide_nums):
    create_Var['negative_data'+str(i)] = negtive_data.iloc[positive_rows*i:positive_rows*(i+1),:]

动态生成变量

20220112

https://blog.csdn.net/weixin_30498921/article/details/95287956
traceback.print_exc()的用法

20220110

def save_to_result(a):
    '''
    保存到结果表中
    :param result_save: 结果保存表
    :param group: 现在要追加保存的记录
    :return: 追加后的结果
    '''
    if a > 0:
        b=1
    else:
        b=2
    return b
result = save_to_result(0)
result

函数多分支结果返回,有判断的情况下也只需要写一个return

20220108
在这里插入图片描述
Counter是求的列表里面每个原始的频数

https://www.runoob.com/python/att-list-count.html
list.count(element)
求某个元素的格式
len(list)总个数
python列表计数函数

20211230

https://www.cnblogs.com/pengpp/p/9833349.html
python调用执行shell命令最简单

20211224

https://blog.csdn.net/qq_36134437/article/details/103245281

Python中的Counter.most_common()方法
返回序列中频率最高的词

20211217

trycatch适合于需要程序不中断
偶尔的中间错误可以忽略
比如for循环中的某个处理具体值的处理
读数据的时候忽略某个错误数据等

https://blog.csdn.net/lwgkzl/article/details/81059433
https://www.runoob.com/python/python-exceptions.html

python中的try-catch-finally-else简介
else 没有异常的时候执行
https://www.zhihu.com/question/266526582/answer/310526097

20211214

https://blog.csdn.net/nominior/article/details/114673923
取消pytest 改成unittest

20211130

a &= b 等价于 a = a & b

https://www.runoob.com/python/att-dictionary-fromkeys.html

https://www.cnblogs.com/huashiyiqike/p/3857231.html
关闭垃圾回收

Python 字典(Dictionary) fromkeys()方法

20211129

TypeError: not all arguments converted during string formatting
    logger.debug("Old Shape: " ,table.shape)
    上面直接是不行的,需要加%s或者format
    logger.debug("Old Shape: ".format(table.shape))

20211123

TypeError: expected string or bytes-like object
遇到空值会报错

20211117

https://blog.csdn.net/zhongbeida_xue/article/details/78973936
偏函数把函数当做第一个参数传入

20211012

python中使用statsmodels这个包建立logit模型出现singular matrix?
https://blog.csdn.net/zzw000000/article/details/89714720
https://www.zhihu.com/question/60149603?sort=created
没有逆矩阵

statsmodel.api.Logit: valueerror array must not contain infs or nans
里面确实含有无穷大

ValueError: Input contains infinity or a value too large for dtype('float64').

gyh_zd = preprocessing.scale ( gyh_zd )
已经是比率值的列且存在0值的时候不需要再归一化
否则会报这个错误

20211006

在这里插入图片描述
非通过导包运行另一个模块的函数

20210923

在这里插入图片描述
反斜杠分行

https://www.runoob.com/js/js-errors.html
try catch throw

20210913

https://www.runoob.com/python/python-func-locals.html
python locals

import tempfile
with tempfile.TemporaryDirectory() as job_dir:
if dsl:
python生成临时文件夹
在这里插入图片描述
系统功能命令 就不能通过python调试了?

20210902

https://mp.weixin.qq.com/s/Yjlr3XDksN3gWI5SUi1HdA
3大利器推荐,帮你写出规范漂亮的python代码

No matching distribution found for tensorflow==2.3.4 (from fate-client)
很有可能是pip 没有升级

“xxx” .replace(“某个变量字符串”,str('变量)) 把整体字符串中的变量做替换

https://www.cnblogs.com/fengshuihuan/p/7105545.html
itertools 模块详解

20210816

https://www.cnblogs.com/stuqx/p/7291948.html
https://blog.csdn.net/cxcxrs/article/details/82459800
对字典遍历

在这里插入图片描述
python 制作安装包

AttributeError: ‘str‘ object has no attribute ‘decode‘解决方法
https://blog.csdn.net/qq_43192819/article/details/108981008

https://www.cnblogs.com/kaituorensheng/p/3554571.html
全角半角转换

https://blog.csdn.net/xCyansun/article/details/79672634
Python中关键字global与nonlocal的区别
global 可用于模块的任何地方 相当于 类里面的self.属性
nolocal范围指扩展到上一级函数 而不是整个模块

https://mp.weixin.qq.com/s/xcmyztXTUfbXlXibKcMKbg
python执行shell命令 可以重启一个进程

20210813

在这里插入图片描述
获取当前py模块的进程号

在这里插入图片描述
在这里插入图片描述
获取父进程的pid pycharm的pid

无限重启监控程序
python通过shell脚本重启程序就不会在一个进程里面

20210812

https://www.cnblogs.com/mzct123/p/5663311.html
get-pip.py的 使用

https://pan.baidu.com/s/13rIiIcpaQpO7iKexhxKoRA
get-pip.py 下载
Python get-pip.py文件

做项目时发现get-pip.py这个文件比较难下载,将此文件分享给各位需要的人!
文件来源:https://bootstrap.pypa.io/get-pip.py
如果链接打不开请至网盘自行下载:链接: https://pan.baidu.com/s/13rIiIcpaQpO7iKexhxKoRA 提取码: r2mb

20210811

https://blog.csdn.net/baoxiao7872/article/details/90340163
Python os.removedirs() 方法
python 删除文件或路径下的文件

20210803

https://www.zhihu.com/question/41701160/answer/92136065
重点可用
http://c.biancheng.net/view/2690.html

python修改程序名

https://blog.csdn.net/qq_23860475/article/details/87364985
soted 字典排序

https://blog.51cto.com/luyaliang/1909596
Python自定义进程名 但是不管用貌似

https://blog.csdn.net/zuihongyan518/article/details/96978200
Math.round(),Math.ceil(),Math.floor()的区别

20210802

response=requests.post('https://pc.api.longyiyy.com/api/login/userLogin',headers=headers,cookies=cookies,data=data)
print(response.content.decode("unicode_escape"))

python unicode 解码

20210726

dir查看方法有哪些熟悉
在这里插入图片描述
递归的另一种实现

20210724

在这里插入图片描述
反编译看源码
追踪

20210630

https://zhuanlan.zhihu.com/p/369464796
递归调试

https://www.cnblogs.com/yucloud/p/10680395.html
递归再理解
假设两层 最里层执行到return之后 外面层再返回

20210628

for循环的本质

for x in [1, 2, 3, 4, 5]:
    pass
# 首先获取可迭代对象
it = iter([1, 2, 3, 4, 5])
while True:
    try:
        next(it)
    except StopIteration:
        # 遇到StopIteration就跳出循环, 且自动频闭StopIteration异常
        break

20210623

python判断文件和文件夹是否存在、是否为空,创建文件夹
>>> import os
>>> os.path.exists('d:/assist')
True
>>> os.path.exists('d:/assist/getTeacherList.py')
True
>>> os.path.isfile('d:/assist')
False
>>> os.path.isfile('d:/assist/getTeacherList.py')
True
>>> os.makedirs('d:/assist/set')
>>> os.path.exists('d:/assist/set')
True

 if not os.listdir(f): #判断文件夹是否为空 f是一个文件夹的绝对路径

https://www.cnblogs.com/sea-stream/p/11396072.html

20210622

https://www.jb51.net/article/206394.htm
python forward
shili=aa(data)

因为 aa() 等价于 调用了 call , 在函数__call__中 又调用了 forward
等价于 aa.forward(data)

20210618

if not fast
判断为false

https://blog.csdn.net/tsinghuahui/article/details/89279152
python argparse中action的可选参数store_true的作用
直接运行脚本的时候是 false
如果后面跟了 --xxx xxx 是参数 则为True
设置了默认值的话 以默认值 default 为准

20210610

pickle.UnpicklingError: the STRING opcode argument must be quoted
https://blog.csdn.net/carroll
/article/details/106545918

提示不能build wheel的时候 可以尝试再重新安装一次

json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 555023)
https://blog.csdn.net/m0_37052320/article/details/102558444
json文件中有多个字典

      assert isinstance(self.data, list), "ERROR: data must be in list [train_data,dev_data]"

https://www.runoob.com/w3cnote/c-assert.html
断言并抛出错误
判断是否有错

https://zhuanlan.zhihu.com/p/64487092
@property的介绍与使用
把方法设置为只读方法 不允许更改 类似私有属性的感觉

https://m.runoob.com/python/att-string-isalnum.html
Python isalnum() 方法检测字符串是否由字母和数字组成。
如果 string 至少有一个字符并且所有字符都是字母或数字则返回 True,否则返回 False

https://blog.csdn.net/weixin_38145317/article/details/104971207
collections.OrderedDict()
有序字典 保证存储的顺序与输入的顺序一致

cls代表类,self代表实例
https://jingyan.baidu.com/article/c33e3f483240ecea15cbb533.html

静态方法和类方法的本质区别就在于能不能访问类的属性,而二者的相同之处就是不能访问类的实例属性。
讲二者之间的区别不得不先提到类的属性,类的属性有两种一种是类属性,另一种是类的实例属性。静态方法和类方法的本质区别就在于能不能访问类的属性,而二者的相同之处就是不能访问类的实例属性。

类和实例通过 cls和self 区分

实例方法:可以同时访问类的属性,和实例属性
在这里插入图片描述

类方法:需要访问类的属性而不需要访问实例属性的情况下定义
在这里插入图片描述
静态方法:如果方法不访问类属性/实例属性的情况下定义
在这里插入图片描述

https://www.cnblogs.com/zhou2019/p/10599953.html
configparse模块

20210609

https://www.cnblogs.com/xybaby/p/6280313.html
https://blog.csdn.net/huyoufu200920201078/article/details/90641105

getattr__函数的作用: 如果属性查找在实例以及对应的类中(通过__dict)失败, 那么会调用到类的__getattr__函数, 如果没有定义这个函数,那么抛出AttributeError异常。由此可见,__getattr__一定是作用于属性查找的最后一步。

python 的内建属性__getattr__的妙用

https://www.cnblogs.com/monogem/p/9765199.html
Python的__getattr__方法学习
重点 如果调用的属性没有 就用 __getattr__生成或者报无此属性的错误

https://blog.csdn.net/fu6543210/article/details/86694549
shutil.copy()与shutil.copytree()的具体用法

__new__方法与__init__方法
https://blog.csdn.net/qq_41020281/article/details/79638370

  def __deepcopy__(self, memo):
        if id(self) in memo:
            return memo[id(self)]
        else:
            result = type(self)(self.data.clone(), self.requires_grad)
            memo[id(self)] = result
            return result

https://blog.csdn.net/yueguanghaidao/article/details/25613887

reduce_ex
https://www.cnblogs.com/angelyan/p/11079267.html

20210608

协程交出控制权给外层的实践循环

20210607

break 也可直接退出while循环

https://blog.csdn.net/fu6543210/article/details/86694549
python中shutil.copy()与shutil.copytree()的具体用法

https://blog.csdn.net/klordy_123/article/details/87349433
判断文件是否存在

20210604

最大递归层数 999

for c in ‘AB’
yield c
等价于 yield from ’AB‘

在这里插入图片描述

协程:next 预激 调用传入的值
yield 相当于return
等号左边接收出入的值 b接收28,c接收99

在这里插入图片描述
一次send 相当于左边接收了send的值 也return了当前yield后面的值

在yield处停止 然后
next 或 send 再激活协程

在这里插入图片描述
相当于每next或send 时候 都运行一遍 1,2,3步 逆时针的步骤

在这里插入图片描述

result 直接获取yield from 的结果
在这里插入图片描述
yield的作用

在这里插入图片描述
运行之前预先激活

括号调用生成器的时候,生成器的状态是 created
next 之后 生成器的状态是 suspend

20210603

在这里插入图片描述
计时器

一个进程可以开多个线程
在这里插入图片描述
在这里插入图片描述

递归锁
信号量
gil锁
互斥锁
线程池,进程池 不能来一个开一个 不能要求1万个也开一万个

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值