【问题标题】:How to input a string or a sentence and output the corresponding value(s) from the dictionary如何输入字符串或句子并从字典中输出相应的值
【发布时间】:2020-10-06 17:54:12
【问题描述】:

当我执行 print(d) 时,我能够打印键:值组合。现在我的目标是当我在即时通讯中输入一条消息时。你迟到了。它应该打印回来你为什么迟到。目的是将句子拆分为单词,并在可用的情况下将其替换为关联的文本值,否则保留原始单词

这是一个学校作业,我只是在寻找一些帮助

这就是我的字典的一部分:

{'r': 'are\n', 'y': 'why\n', 'u': 'you\n', 'ttyl': 'talk to you later\n', 'l8': 'late\n', 'brb': 'be right back\n', 'lol': 'laughing out loud\n', 'bbl': 'be back later\n', 'tldr': "too long; didn't read\n", 'rofl': 'rolling on floor laughing\n', 'gtg': 'got to go\n'}
d = {}
with open("abbreviations.txt") as abb:
    for line in abb:
        (key, val) = line.split(":")
        d[key] = val

print(d)

im = input("Enter message here: ")

【问题讨论】:

  • 在脚本末尾添加 reason = d.get(im,'no idea why..') print(reason)

标签: python


【解决方案1】:

这是你要找的吗?

d = {}
with open("abbreviations.txt") as abb:
    for line in abb:
        (key, val) = line.split(":")
        d[key] = val

print(d)

im = input("Enter message here: ")
message = ' '.join([d[s] if s in d else s for s in im.split()])

【讨论】:

    【解决方案2】:

    肯定有更紧凑的方法可以做到这一点,但这应该有助于您在编码时理解和探索更多内容。

    您应该知道的是,您可以使用字典中的dict.get(<key>) 方法来检索值。如果这不存在,它将返回None

    d = {}
    with open("abbreviations.txt") as abb:
        for line in abb:
            (key, val) = line.split(":")
            d[key] = val
    
    print(d)
    
    im = input("Enter message here: ")
    
    final_prhase = ""
    
    for abb in im.split():
        temp = d.get(abb) or abb
        final_prhase += "{} ".format(temp)
    
    print("Your are saying: {}".format(final_prhase))
    

    【讨论】:

    • 您在 final_phrase 中的单词之间缺少空格。此外,我认为输入消息不应仅包含缩写。
    • 您在空格上是对的,但我不知道@baldeman 如何期望输入。我按照他的要求提供了另一个例子,然后他可以选择做什么。无论如何,让我将您的建议添加到我的代码中。谢谢
    • 可以选择的选项没有错。但是,@Malan 明确指出,字典中没有出现的单词应该按原样使用。在您的解决方案中,它们会丢失。
    • 傻我,我的坏。现已修复
    • 非常感谢。这真的很有帮助
    猜你喜欢
    • 1970-01-01
    • 2023-02-14
    • 2015-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多