一、快速实现字频统计
from collections import Counter
words = '''我明白你的意思,你的意思就是想意思意思,但是你不明白我的意思,我的意思是你不用意思意思。'''
word_counts = Counter(words)
top_three = word_counts.most_common(3)
print(top_three)
二、汉字转拼音
import pypinyin
words = "床前明月光"
pypinyin.pinyin(words)
# 输出:[['chuáng'], ['qián'], ['míng'], ['yuè'], ['guāng']]
三、查看某个文件夹里是否有python文件(或其他格式文件)
import os
files = os.listdir("E:\\testfile\\")
if any(name.endswith('.py') for name in files):
print(1)
四、快速打印字符串
row = ["我", "爱", "python"]
print(*row,sep="")
五、计算两个日期间隔天数
from datetime import date
d1 = date(2020,1,1)
d2 = date(2020,9,13)
print(abs(d2-d1).days)
六、字符串拆解为键值对
比如'x=11,y=20'拆解成{'x': 42.0, 'y': 1.0}
kvp = lambda elem,t,i: t(elem.split('=')[i])
parse_kvp_str = lambda args : dict([(kvp(elem,str,0), kvp(elem,float,1)) for elem in args.split(',')])
parse_kvp_str('x=11,y=20')
七、变量值交换
八、将值追加到字典某个键下的列表中
d = {}
d.setdefault(2, []).append(23)
d.setdefault(2, []).append(11)
d[2]
九、返回列表中出现次数最多的元素
test = [1, 2, 3, 5, 2, 2, 3, 1, 2, 6, 2]
print(max(set(test), key = test.count))
十、查看某个变量占用内存的大小
import sys
x = 1
print(sys.getsizeof(x))
十一、随机返回几个字母组成的单词
import string, random
randword = lambda n: "".join([random.choice(string.ascii_letters) for i in range(n)])
# 输出:'qsNWZF'
十二、从混乱的字符串中分解出单词
words = lambda text: ''.join(c if c.isalnum() else ' ' for c in text).split()
words('Johnny.Appleseed!is:a*good&farmer')
# 输出:['Johnny', 'Appleseed', 'is', 'a', 'good', 'farmer']
十三、打印进度条
import time
import sys
for progress in range(100):
time.sleep(0.1)
sys.stdout.write("Download progress: %d%% \r" % (progress) )
sys.stdout.flush()
十四、快速反转字符串
a = 'Python is a powerful languange.'
print(a[::-1])
十五、找出两个列表中不一样的元素
list1 = ['Scott', 'Eric', 'Kelly', 'Emma', 'Smith']
list2 = ['Scott', 'Eric', 'Kelly']
set1 = set(list1)
set2 = set(list2)
list3 = list(set1.symmetric_difference(set2))
print(list3)
十六、删除列表中的重复项
listNumbers = [20, 22, 24, 26, 28, 28, 20, 30, 24]
list(set(listNumbers))
十七、将两个列表变成字典
ItemId = [54, 65, 76]
names = ["Hard Disk", "Laptop", "RAM"]
itemDictionary = dict(zip(ItemId, names))
print(itemDictionary)
十八、移除字符换中的标点
punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~,。!?'''
my_str = "你好,!!我的网名叫作:隔-壁-老-王。"
no_punct = ""
for char in my_str:
if char not in punctuations:
no_punct = no_punct + char
print(no_punct)
十九、创建一个文件(如果文件不存在)
import os
MESSAGE = '该文件已经存在.'
TESTDIR = 'testdir'
try:
home = os.path.expanduser("~")
print(home)
if not os.path.exists(os.path.join(home, TESTDIR)):
os.makedirs(os.path.join(home, TESTDIR))
else:
print(MESSAGE)
except Exception as e:
print(e)
二十、从函数中返回多个值
def f():
return 1,2,3,4
a,b,c,d = f()
print(a,b,c,d)