python函数、字典运用.get来索引表情

该代码定义了一个情感分析函数,通过用户输入的情绪文字,利用字典匹配转换为相应的情感标签。例如,:(转为/伤心,:)转为/开心。函数首先对输入进行分词,然后遍历字典获取对应情感标签,最后返回处理后的输出。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

def emotional():
    words = emotion.split(' ')
    art = {
        ":(": "/伤心",
        ":)": "/开心",
        ":|": "/还好",
    }
    output=" "
    for ch in words:
        output +=art.get(ch,ch) + " "
    return(output)


emotion = input("how do you felling?: ")
print(emotional())

这个代码是我练习,感觉思路有点绕不过来写的。解释一下:

首先:

def emotional():                #这个是定义一个函数
    words = emotion.split(' ')        #split是将输入的一段话分开,给words
    art = {                        #字典里面一个键值对应着一个信息
        ":(": "/伤心",
        ":)": "/开心",
        ":|": "/还好",
    }
    output=" "                        #设置输出的内容,就是先定义
    for ch in words:                #words就是输入的内容,遍历有没有字典里面的键值比如:":("
        output +=art.get(ch,ch) + " "    #用.get函数从words获取字典键值对应的信息输出output
    return(output)


emotion = input("how do you felling?: ")        #输入信息,传递给word,也就是emotion.split(' ')
print(emotional())                                #打印函数的return
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值