【问题标题】:Print one word from a list within a dictionary (python)从字典中的列表中打印一个单词(python)
【发布时间】:2016-09-03 14:27:06
【问题描述】:

我希望我的程序只打印字典中列表中的一个随机单词,但我似乎无法获得正确的语法来执行此操作。我尝试使用 popitem() 从列表中获取随机值,但它似乎不起作用。这是我的代码:

import random

thesaurus = {
              "happy":["glad",  "blissful", "ecstatic", "at ease"],
              "sad"  :["bleak", "blue", "depressed"]
            }

# input
phrase = input("Enter a phrase: ")

# turn input into list
part1 = phrase.split()
part2 = list(part1)

newlist = [] 
for x in part2:
    s = thesaurus.get(x, x)
    newlist.append(s)

print (newlist)

例如,如果输入是

i am happy

预期的输出是

i am glad

或字典中列表中的任何随机单词。

但是,现在我的输出看起来像这样:

['i', 'am', ['glad', 'blissful', 'ecstatic', 'at ease']]

我知道这涉及到另一个线程,但它似乎没有解决这个特定问题。

任何帮助将不胜感激!

编辑:

如果我扩展此公式以处理包含一长串单词的导入文件,我将如何更改代码?

newDict = {}
with open('thesaurus.txt', 'r') as f:
    for line in f:
        splitLine = line.split()
        newDict[(splitLine[0])] = ",".join(splitLine[1:])

print ("Total words in thesaurus: ", len(newDict))

# input
phrase = input("Enter a phrase: ")

# turn input into list
part1 = phrase.split()
part2 = list(part1)

# testing input
newlist = []
for x in part2:
    s = newDict[x].pop() if x in newDict else x
    s = random.choice(newDict[x]).upper() if x in newDict else x
    newlist.append(s)


newphrase = ' '.join(newlist)
print (newphrase)

“同义词库”文件中的行文本示例:

abash,humility,fear

【问题讨论】:

  • thesaurus.get(x, x) 是什么意思?
  • @Arman 第二个x 是默认值。该语句本质上的意思是“获取与键 x 关联的值,或者如果没有找到值则返回 x

标签: list python-3.x dictionary random


【解决方案1】:

此解决方案不会修改您的原始字典

for x in part2:
    s = random.choice(thesaurus.get(x, [x]))
    newlist.append(s)

您的字典将字符串映射到字符串列表,因此您的原始解决方案将列表放在字符串的位置。 random.choice 从列表中选择一个随机元素。

【讨论】:

    【解决方案2】:

    map你的输出到这个。您也可以将列表连接在一起以形成您想要的字符串。

    newList= list(map(lambda x:  random.choice(x) if type(x) == list else x, newList))
    
    print(" ".join(newList))
    

    【讨论】:

    • type(x) 通常不是类型检查的好方法......更倾向于使用isinstance,这有一个额外的问题是必须重新遍历列表,有效地加倍时间复杂度(可能不是什么大问题)...
    • 有人可以编辑我的帖子以正确格式化吗? :( 不确定如何在移动设备上进行操作。
    • 因为它有效并且您在移动设备上编写了它,但还是给 +1 了:P
    【解决方案3】:

    您可能想要使用random 模块:

    例子:

    import random
    >>> l = list(range(10))
    >>> random.choice(l)
    5
    >>> random.choice(l)
    9
    

    在你的情况下,你可以这样做:

    print (" ".join(random.choice(thesaurus[x]) if x in thesaurus else x for x in part2))
    

    例子:

    >>> import random
    >>> phrase = "I am feeling sad that he left, but that's okay because I'm happy he will be back soon"
    >>>
    >>> thesaurus = { "happy":["glad",  "blissful", "ecstatic", "at ease"],
    ...               "sad"  :["bleak", "blue", "depressed"]
    ...             }
    >>> print (" ".join(random.choice(thesaurus[x]) if x in thesaurus else x for x in phrase.split()))
    I am feeling bleak that he left, but that's okay because I'm blissful he will be back soon
    

    【讨论】:

    • 谢谢!如果我将此公式扩展为使用包含一长串单词的导入文件,我将如何更改您在上面发布的代码?我编辑了原始帖子以显示扩展代码,非常感谢任何帮助!
    【解决方案4】:
     thesaurus.get(x,x)
    

    表示thesaurus[x] if x in thesaurus else x

    因为thesaurus["happy"] 是一个列表,所以它返回整个列表

    我想你只想得到一件物品

    for x in part2:
       s = thesaurus[x].pop() if x in thesaurus else x # returns first word (and removes from list)
       s = thesaurus[x][0] if x in thesaurus else x # returns first word without removing it
       s = random.choice(thesaurus[x])if x in thesaurus else x # returns random word
       newlist.append(s)
    

    【讨论】:

    • 这会缩小列表,不是吗?这似乎不合适。
    • 他说他试过“popitem”所以我想也许是
    • 谢谢!如果我将此公式扩展为使用包含一长串单词的导入文件,我将如何更改您在上面发布的代码?我编辑了原始帖子以显示扩展代码,非常感谢任何帮助!
    猜你喜欢
    • 2017-07-02
    • 1970-01-01
    • 2017-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-06
    • 1970-01-01
    • 2013-02-16
    相关资源
    最近更新 更多