【问题标题】:Converting Input Strings Into Dictionaries将输入字符串转换为字典
【发布时间】:2023-01-28 22:20:43
【问题描述】:

我已经多次尝试将输入数据转换为另一个字符串并在更新版本中打印出来。

strings = input("What is the sentence?") # inputs data

words = strings.split() # splits every word into a string
words = { # dictionary
    'swimming': 'swimming pool', 
    'walking': 'pedestrian road'
    'flying': 'airplane'
        }

例如:input = 'I am swimming today.' 输出='游泳池'

我认为这就像分类一样,但不知道如何将其应用于此。

我找不到任何有帮助的答案...... 请帮助

【问题讨论】:

  • 第一次分配给你会得到一个由空格分隔的字符串列表字符串多变的。然后你立即用字典覆盖它

标签: python dictionary classification text-classification


【解决方案1】:

不要用您的字典覆盖words——而是单独声明您的字典,并遍历单词以查找字典中的条目。

>>> verb_objects = {
...     'swimming': 'swimming pool', 
...     'walking': 'pedestrian road',
...     'flying': 'airplane',
... }
>>> sentence = "I am swimming today."
>>> [verb_objects[word] for word in sentence.split() if word in verb_objects]
['swimming pool']

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-09
    • 1970-01-01
    • 1970-01-01
    • 2021-07-25
    • 1970-01-01
    相关资源
    最近更新 更多