美文网首页
辽经干python 元组和字典(2)

辽经干python 元组和字典(2)

作者: __method__ | 来源:发表于2021-03-31 11:46 被阅读0次
# 元组  tuple 和列表很像, 只不过不能修改
b = ("鲁班", 333, 4455, 44.2)
print(b)
print(type(b)) #<class 'tuple'>
# 访问
print(b[0])
print(b[1])
# 不支持修改, 增加 删除操作
# b[0] = 88 #TypeError: 'tuple' object does not support item assignment
# 只有一个元素的元组
c = ("haha", )
print(type(c))

字典

# 字典
#  映射  一一对应   key - value
# hero_info = ["安琪拉", 13, 5 , 6, 7]  # 列表是靠索引访问数据的
hero_info = {"name":"安琪拉", "grade":13, "K":5, "D":6, "A":7}
# 字典的基本操作
# 字典是靠键访问字典中的值
# 1
print(hero_info["K"])
print(hero_info["name"])
# print(hero_info["blood"]) # KeyError: 'blood'

# 2
print(hero_info.get("name"))
print(hero_info.get("blood")) # None
print(hero_info.get("blood", 2000)) # 可以设置默认值
# 字典的修改
hero_info["name"] = "鲁班七号"
print(hero_info)

# 字典的增加
hero_info["blood"] = 2000
print(hero_info)

# 字典的删除
# del hero_info
# print(hero_info) #NameError: name 'hero_info' is not defined
del hero_info["grade"]
print(hero_info)
# 获取所有键
print(list(hero_info.keys()))
# 获取所有值
print(list(hero_info.values()))
# 获取所有键值
print(list(hero_info.items()))
# 字典的遍历
for k, v in hero_info.items():
    print(k,'------->', v)

词频统计


text = """
fake wings
shine bright morning light
now in the air the spring is coming
sweet blowing wind
singing down the hills and valleys
keep your eyes on me
now we're on the edge of hell
dear my love sweet morning light
wait for me you've gone much farther too far
"""
print(type(text))
# 字符串变成列表
text_list = text.split()
print(text_list)
# 词频统计{"fake":3, "wings":5}
counts = {}
for word in text_list:
    # counts[word] = 字典中原来这个单词出现的次数 + 1
    # counts[word] = counts[word] + 1
    counts[word] = counts.get(word, 0) + 1
print(counts)

词云

#
text = """
fake wings
shine bright morning light
now in the air the spring is coming
sweet blowing wind
singing down the hills and valleys
keep your eyes on me
now we're on the edge of hell
dear my love sweet morning light
wait for me you've gone much farther too far
"""
# 安装第三方库
# pip install 名字
# pip install wordcloud
# pip install imageio
# 导入第三方库
import imageio
from wordcloud import Word[图片上传中...(qiaobusi.png-102248-1617162348778-0)]
Cloud
mask = imageio.imread('qiaobusi.png')
wc = WordCloud(
    height=600,
    width=600,
    background_color= "white", 
    mask = mask
)
file = wc.generate(text)
file.to_file("歌词.png")


相关文章

网友评论

      本文标题:辽经干python 元组和字典(2)

      本文链接:https://www.haomeiwen.com/subject/kpcohltx.html