如果列表中有一个小写元素而不将列表更改为小写

if a lowercase element is in the list without changing the list to lowercase

我正在尝试创建一个程序,用字典中的单词替换输入中输入的任何单词。这是词典:

slang = {'phone': 'dog and bone', 'queen': 'baked bean', 'suit': 'whistle and flute', 'money': 'bees and honey', 'dead': 'brown bread', 'mate': 'china plate', 'shoes': 'dinky doos', 'telly': 'custard and jelly', 'boots': 'daisy roots',  'road': 'frog and toad', 'head': 'loaf of bread', 'soup': 'loop the loop', 'walk': 'ball and chalk', 'fork': 'roast pork', 'goal': 'sausage roll', 'stairs': 'apples and pears', 'face': 'boat race'} 

这是一个输出示例。

Sentence: I called the Queen on the phone
I called the baked bean on the dog and bone

我已经尝试编写这个程序的代码,并且我已经让它打印出输出(几乎)。我只是不知道如何查询输入的单词是否在字典中,而不用小写版本替换大写的单词。

这是我的输出示例:

Sentence: I called the Queen on the phone
i called the baked bean on the dog and bone

这是我试过的代码,我意识到出现这个问题是因为我在开头将句子设置得较低。我试图在进入 for 循环之前将 'word' 设置为较低,但这也不起作用,因为 'word' 在 for 循环之前是未知的。

slang = {'phone': 'dog and bone', 'queen': 'baked bean', 'suit': 'whistle and flute', 'money': 'bees and honey', 'dead': 'brown bread', 'mate': 'china plate', 'shoes': 'dinky doos', 'telly': 'custard and jelly', 'boots': 'daisy roots',  'road': 'frog and toad', 'head': 'loaf of bread', 'soup': 'loop the loop', 'walk': 'ball and chalk', 'fork': 'roast pork', 'goal': 'sausage roll', 'stairs': 'apples and pears', 'face': 'boat race'}
new_sentence = []
sentence = input("Sentence: ").lower()
words_list = sentence.split()
for word in words_list:
  if word in slang:
    replace = slang[word]
    new_sentence.append(replace.lower())
  if word not in slang:
    new_sentence.append(word)
separator = " "
print(separator.join(new_sentence))

非常感谢!

您可以使用list comprehension代替,

slang = {'phone': 'dog and bone', 'queen': 'baked bean', ...}

Sentence = "I called the baked bean on the dog and bone"
print(" ".join(slang.get(x.lower(), x) for x in Sentence.split()))

I called the baked bean on the dog and bone

类似于下面的内容:

slang = {'phone': 'dog and bone', 'queen': 'baked bean'}

def replace_with_slang(sentence):
  words = sentence.split(' ')
  temp = []
  for word in words:
    temp.append(slang.get(word,word))
  return ' '.join(temp)


print(replace_with_slang('I called the phone  It was the queen '))