lijiazheng-Python-day05

本文介绍了Python字典的各种操作,包括遍历、获取键值、转换为列表、字典推导式以及字符串常用方法。还展示了如何进行词频统计,通过实例演示了如何从文本中提取关键词并计数。此外,讲解了字符串的分割、去空格、替换和连接等操作。最后,探讨了如何根据给定文本生成词频统计的字典。
摘要由CSDN通过智能技术生成

字典操作与遍历

stu_info = {'name': 'eric', 'age': 19, 'addr': '铁岭的', 11: 666}
print(stu_info)

# 获取字典中所有的键
print(list(stu_info.keys()))
# 获取字典中所有的值
print(list(stu_info.values()))
# 获取字典中所有的键 值  字典变成列表
print(list(stu_info.items()))

# 列表变成字典
ls = [('name', 'eric'), ('age', 19), ('addr', '铁岭的'), (11, 666)]
print(dict(ls))

for k, v in stu_info.items():
    print(k,v)

# 使用len
print(len(stu_info))

字典推导式

from random import randint
import string
print(string.ascii_uppercase)
print(string.ascii_uppercase[:7])  # ABCDEFG
print(string.ascii_lowercase)
print(string.ascii_letters)
# {k: v for 临时 in 迭代对象}
print([i for i in range(10)])
print({i: 1 for i in range(10)})
print({1: i for i in range(10)})
print({i: i for i in range(10)})
print({str(i): i for i in range(10)})
print({6: 6 for i in range(10)})
print([i for i in "ABCDEFG"])
print([i for i in string.ascii_uppercase[:7]])
print([f'student{i}' for i in string.ascii_uppercase[:7]])
# 学生做key 成绩做value
score_d= {f'student{i}': randint(30, 100) for i in string.ascii_uppercase[:7]}
print(score_d)
print({x for x in score_d})
print({x for x in score_d.items()})
print({x[0]:x[1] for x in score_d.items()})
print({x[1]:x[0] for x in score_d.items()})
print([i for i in [111, 222, 3333] if i > 221])

#选出字典中成绩大于 60的
print({ k: v for k,v in score_d.items() if v >=60})

字符串常用方法

import string
# 字符串常用方法
# ''  和 " " 声明的 支持切片
# 字符串迭代
# for i in "JiazhenLi":
#     print(i)
print(list("JiazhenLi"))
name = "Python C++ Java"
path = 'C:/Users/Eric/Documents'
# 1.字符串 分割  --> 列表 默认按照空格分割
print(name.split())
print(name.split('+'))
print(path.split('/'))
print(path.split())
# 2.去两端空格
name = " Python C++ Java  "
print(len(name))
name = name.strip()
print(len(name))
# 3.替换
price = '$9.9'
price = price.replace("$", "")
print(price)
price = float(price)
price = 10*price
print(price)
print([222, 111]*3)
# 4. join 列表变成字符串
print("".join([str(i) for i in [111, 222, 333, 444]]))
print(" ".join([str(i) for i in [111, 222, 333, 444]]))
print("/".join([str(i) for i in [111, 222, 333, 444]]))
print("_".join([str(i) for i in [111, 222, 333, 444]]))
print([i for i in string.ascii_uppercase[:8]])
print("_".join(string.ascii_uppercase[:8]))


词频统计


text = "When you face the world alone, alone When you face the world alone, When you face the world alone"
text = text.replace(",", "")
word_list = text.split()
print(word_list)

# {"When": 4, "face":5}
counts = {}
# for word in word_list:
#     counts[word] = 0
# print(counts)
for word in word_list:
    # counts[word] = counts[word] +  1
    counts[word] = counts.get(word, 0) +  1
print(counts)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值