从字典中打印列表中的一个单词(Python)

4

我希望我的程序能够从字典中的列表中随机打印出一个单词,但是我似乎无法找到正确的语法来实现。我尝试使用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)

“thesaurus”文件中的行文本示例:

abash,humility,fear

thesaurus.get(x, x) 的意思是什么? - ᴀʀᴍᴀɴ
2
@Arman 第二个 x 是默认值。该语句的本质意思是:“获取与键 x 关联的值,如果没有找到任何值,则返回 x”。 - smac89
4个回答

2
 thesaurus.get(x,x)

意思是 如果x在词库中则返回thesaurus[x],否则返回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)

这会缩小列表,不是吗?这似乎不太合适。 - Rushy Panchal
他说他尝试了“popitem”,所以我想也许是这样。 - Joran Beasley
谢谢!如果我想将这个公式扩展到使用一个包含大量单词的导入文件,我需要如何更改您上面发布的代码?我已经编辑了原帖以显示扩展代码,非常感谢您的帮助! - Danny Garcia

1

2
“type(x)”通常不是一种好的类型检查方式...更好的方法是使用“isinstance”,但这会导致必须重新遍历列表,有效地使时间复杂度加倍(可能不是什么问题)... - Joran Beasley
有人可以编辑我的帖子以正确格式呈现吗?:(不确定如何在手机上操作。 - mattsap
1
既然它能正常工作而且你是在手机上编写的,我就给一个+1吧 :P - Joran Beasley

1
你可能想要使用 随机数 模块:
示例:
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

谢谢!如果我想将这个公式扩展到使用一个包含大量单词的导入文件,我需要如何更改您上面发布的代码?我已经编辑了原帖以显示扩展代码,非常感谢您的帮助! - Danny Garcia

0

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

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

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接