栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Python实用小技巧(五)

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python实用小技巧(五)

# attrgetter() 函数通常比lambda函数效率高点 同样和 itemgetter()函数一样 可以对 # 对象多个属性进行排序 同样可以作用于 min() max()之类的函数 2. 审查清理文本字符串

文本清理问题会涉及到包括文本解析与数据处理等问题 比如先将字符串标准化 然后使用 replace 等函数替换或者删除字符

import sys
import unicodedata
s pýtĥöñfistawesomern 
print(s)
remap {
 ord( t ): ,
 ord( f ): ,
 ord( r ): None # Deleted
a s.translate(remap)
print(a)
print( # * 50)
# 进一步构建更强大的表格 比如删除所有和音符
cmb_chrs dict.fromkeys(c for c in range(sys.maxunicode)
 if unicodedata.combining(chr(c)))
b unicodedata.normalize( NFD , a)
print(b)
print(b.translate(cmb_chrs))
# 上面的例子中 使用 dict.fromkeys 方法构建一个字典 每个 unicode和音符作为键对应的值全部为 None
# 然后使用 unicodedata.normalize() 将原始输入标准化为分解形式字符
# 然后再调用 translate 函数删除所有重音符?

这样可以直接替换掉文中的多余字符。

3. unicode文本标准化

可以将Unicode编码的字符转成正常的字符串。但处理unicode 字符串需要确保所有字符串在底层有相同表示

# 处理 unicode 字符串 需要确保所有字符串在底层有相同表示
import unicodedata
s1 Spicy Jalapeu00f1o 
s2 Spicy Jalapenu0303o 
print(s1)
print(s2)
print(s1 s2)
print(s1 s2)
print(len(s1))
print(len(s2))
print( * * 50)
# 需要比较字符串的程序中使用字符多种表示可能会产生问题
# 需要先将文本标准化
t1 unicodedata.normalize( NFC , s1)
t2 unicodedata.normalize( NFC , s2)
print(t1 t2)
print(ascii(t1))
t3 unicodedata.normalize( NFD , s1)
t4 unicodedata.normalize( NFD , s2)
print(t3 t4)
print(ascii(t3))
# normalize 第一个参数指定字符串标准化的方式 NFC 表示字符串应该是整体组成
# 而 NFD 表示字符应该分解为多个组合字符表示
4. 指定列宽格式化字符串

使用 textwrap 模块来格式化字符串的输出。比如 假如你有下列的长字符串 使用textwrap后 它们只会显示在一个指定的范围宽度内

import textwrap
s Look into my eyes, look into my eyes, the eyes, the eyes, 
the eyes, not around the eyes, don t look around the eyes, 
look into my eyes, you re under. 
print(textwrap.fill(s, 70))
print(textwrap.fill(s, 40))
print(textwrap.fill(s, 40, initial_indent ))
print(textwrap.fill(s, 40, subsequent_indent ))
# textwrap 模块对于字符串打印是非常有用的 
# 特别是当你希望输出自动匹配终端大小的时候。
5.defaultdict的使用

使用普通的字典时 用法一般是dict {},添加元素的时候dict[element] value即可 调用的时候也是如此 dict[element] xxx,但前提是element字典里 如果不在字典里就会报错 这时defaultdict就能排上用场了 defaultdict的作用是在于 当字典里的key不存在但被查找时 返回的不是keyError而是一个默认值。

from collections import defaultdict
dict1 defaultdict(int)
dict2 defaultdict(set)
dict3 defaultdict(str)
dict4 defaultdict(list)
dict1[2] python 
print(dict1[1])
print(dict2[1])
print(dict3[1])
print(dict4[1])
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/267595.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号