访问字典,用字典中的信息替换用户输入中的项目 [英] Accessing a dict, replacing items in a user input with the information from the dict

查看:65
本文介绍了访问字典,用字典中的信息替换用户输入中的项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试访问一个名为Brands的指令. 然后,我尝试用dict中的信息替换用户输入中的信息.我正在努力打印并替换用户输入的文本.目前,我唯一能做的就是打印出所有表格内容,但所插入的单词不幸地并没有多大帮助.

Im trying to access a dict ive created called Brands. I am then trying to replace information from a user input with information from the dict. I am struggiling to print out and replace text of the user input. Currently the only thing I can get it to do is print out all of the table content, with words inserted which unfortunately doesnt help very much.

BRANDS = {
  'Velcro': 'hook and loop fastener',
  'Kleenex': 'tissues',
  'Hoover': 'vacuum',
  'Bandaid': 'sticking plaster',
  'Thermos': 'vacuum flask',
  'Dumpster': 'garbage bin',
  'Rollerblade': 'inline skate',
  'Asprin': 'acetylsalicylic acid'
}


userinput = input("Sentence: ")
print('a', userinput, 'is', BRANDS[userinput])

这是我的代码必须执行的示例.

Sentence: I bought some Velcro shoes.

Result >>> I bought some hook and loop fastener shoes.

推荐答案

您可以定义一个函数来循环浏览字典并重复执行str.replace:

You can define a function to cycle through your dictionary and perform str.replace repeatedly:

def replacer(x, d):
    for k, v in d.items():
        x = x.replace(k, v)
    return x

userinput = input("Sentence: ")
print(replacer(userinput, BRANDS))

示例:

Sentence: I bought some Velcro shoes.
I bought some hook and loop fastener shoes.

这篇关于访问字典,用字典中的信息替换用户输入中的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆