我希望我的程序只打印字典中列表中的一个随机单词,但我似乎无法获得正确的语法。我尝试使用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
答案 0 :(得分:2)
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)
答案 1 :(得分:1)
map
你的输出到此。您可以将列表一起加入以形成您想要的字符串。
newList= list(map(lambda x: random.choice(x) if type(x) == list else x, newList))
print(" ".join(newList))
答案 2 :(得分:1)
您可能想要使用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
答案 3 :(得分:0)
此解决方案不会修改原始字典
for x in part2:
s = random.choice(thesaurus.get(x, [x]))
newlist.append(s)
您的词典将字符串映射到字符串列表,因此您的原始解决方案会将列表放在字符串的位置。 random.choice
从列表中选择一个随机元素。