Python常用模块:warnings、string、collections、tqdm、rich warnings忽略警告信息。importwarnings# 在控制台中不输出警告信息warnings.filterwarnings(ignore)stringstring 模块提供了一些使用纯 Python 字符串时可能用不到的实用功能主要包括文本常量、字符串模板和自定义格式化。string 模块是字符串方法的补充而非替代。几乎所有常见的字符串操作如大小写转换、查找替换等都应优先使用 Python 字符串自带的方法它们更直接、更高效。而 string 模块则专注于提供一些更特殊的功能。1. 丰富的文本常量告别手动定义string 模块提供了许多预定义的字符串常量常量名说明内容示例string.ascii_letters包含所有 ASCII 字母大小写abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZstring.ascii_lowercase所有 ASCII 小写字母abcdefghijklmnopqrstuvwxyzstring.ascii_uppercase所有 ASCII 大写字母ABCDEFGHIJKLMNOPQRSTUVWXYZstring.digits十进制数字0123456789string.hexdigits十六进制数字包含大小写字母0123456789abcdefABCDEFstring.octdigits八进制数字01234567string.punctuationASCII 标点符号‘!#$%’()*,-./:;?[\]^_{string.whitespaceASCII 空白字符包含空格、制表符、换行等string.printable所有可打印的 ASCII 字符是上述digits,ascii_letters,punctuation,whitespace的集合# 生成一个仅包含字母的随机字符串实际常用random.choicesimportrandomimportstring random_str.join(random.choices(string.ascii_letters,k4))print(random_str)capwords() 函数快速转换单词首字母大写importstring textthe quick brown fox jumps over the lazy dog.# The Quick Brown Fox Jumps Over The Lazy Dog.print(string.capwords(text))collectionsCounter 计数器Counter 是 Python 标准库 collections 模块中的一个字典子类专门用于计数可哈希对象。它的核心功能是统计序列或可迭代对象中每个元素出现的次数。fromcollectionsimportCounter# 从列表创建colors[red,blue,red,green,blue,blue]counterCounter(colors)print(counter)# Counter({blue: 3, red: 2, green: 1})# 从字符串创建统计字符出现次数char_countCounter(abracadabra)print(char_count)# Counter({a: 5, b: 2, r: 2, c: 1, d: 1})tqdmtqdm 是 Python 中一个非常流行的进度条库tqdm 是 Python 中一个非常流行的进度条库。pipinstalltqdm常用参数desc在进度条左侧添加描述文字描述例如“Loading”。unit设置进度单位的名称默认为 ‘it’迭代ncols固定进度条宽度字符数leave进度条完成后是否保留在屏幕上True/Falseposition多行进度条时指定当前进度条的行号用于嵌套循环1. 包装可迭代对象最常用在 for 循环中用 tqdm 包装你的可迭代对象如 list、range、array 等fromtqdmimporttqdmimporttimeforiintqdm(range(100)):time.sleep(0.01)# 模拟耗时操作控制台中不断的刷新进度。2. 手动更新进度对于循环次数未知或需要手动控制进度的情况可以创建一个 tqdm 实例然后调用 update() 方法。fromtqdmimporttqdmimporttime total100pbartqdm(totaltotal)# 创建进度条实例foriinrange(total):time.sleep(0.01)pbar.update(1)# 每次增加1pbar.close()# 关闭进度条with简写自动clsoe()fromtqdmimporttqdmimporttimewithtqdm(total100)aspbar:foriinrange(100):time.sleep(0.01)pbar.update(1)3. 双层循环示例fromtqdmimporttqdmimporttimeforiintqdm(range(3),descOuter):forjintqdm(range(100),descInner,leaveFalse):time.sleep(0.01)4. 与 pandas 集成tqdm 提供了 pandas 的扩展可对 apply 等操作显示进度条importpandasaspdfromtqdmimporttqdm# 注册 pandas 支持tqdm.pandas()dfpd.DataFrame({a:range(100)})df.progress_apply(lambdax:x**2)# 使用 progress_apply 替代 apply5. 在 Jupyter Notebook 中使用若在 Jupyter Notebook 中运行建议使用 tqdm.notebook 子模块以获得更好的显示效果fromtqdm.notebookimporttqdmforiintqdm(range(100)):time.sleep(0.01)rich在 Rich 模块中print 的作用是作为 Python 内置 print 函数的“即插即用”增强版。它能让你在不改变使用习惯的前提下为终端输出添加丰富的样式和色彩使内容更美观、易读。print 方法: 这是 Rich 最快捷的入口。它的函数签名与 Python 的内置 print 完全一致支持 sep、end、file 和 flush 等所有参数。你可以像使用普通 print 一样使用它。自动语法高亮与美化: 当你打印列表、字典等数据结构时Rich 会自动进行语法高亮用不同颜色区分数据类型和美化打印Pretty Print。这使得调试时查看复杂数据变得异常清晰。内置 Console Markup: 你可以在字符串中使用类似 [bold magenta] 的简单标记语法为文本添加颜色和样式如粗体、斜体、下划线PyCharm支持rich需要配置一下在 PyCharm 菜单栏点击 Run - Edit Configurations…。在左侧列表中找到并选中你正在运行的 Python 文件。在右侧的配置面板中找到 Execution 区域。勾选 “Emulate terminal in output console” (模拟终端输出) 选项。点击 OK 保存然后重新运行你的代码。pipinstallrichfromrichimportprintasprintprint([1,2,3])print(Hello, [bold magenta]World[/bold magenta]!)fromrich.consoleimportConsole consoleConsole()console.print(The answer is,42,stylebold green)