用列表中的值替换列表中的单词

问题描述:

我正在尝试创建一个简单的程序,让您输入一个句子,然后将其分割成单独的单词,保存为 splitline 。例如:

I'm trying to create a simple program that lets you enter a sentence which will then be split into individual words, saved as splitline. For example:

the man lives in a house

每个单词将与包含与以下值存储的多个单词相匹配的dict匹配:

Each word will be matched against a dict that contains a number of words stored against values such as:

mydict = {"the":1,"in":2,"a":3}

如果该词存在于dict中,那么我希望用与该值相关联的键替换该单词,以便输出将如下所示:

If the word is present in the dict, then I want the word to be replaced with the key associated with the value so that the output will look like:

1 man lives 2 3 house


$ b $我创建了一些代码,允许我测试每个单词是否存在于dict中,然后可以为句子中的每个单词输出true或false,但是当我尝试用键替换单词时

I created some code that allows me to test if each word exists in the dict which was then able to output 'true' or 'false' for every word in the sentence but when I tried to replace the word with the key from the dict I goit a little stuck.

这是我迄今为止所尝试的:

Here's what I tried so far:

text = input("Enter a sentence \n")
    for word in text:
        splitline = text.split(" ")

mydict = {"the":1,"in":2,"a":3}

for word in splitline:
    if word in dict.keys(mydict):

        #I tried to declare x as the value from the dict
        x = str(dict.values(mydict))

        #newline should be the original splitline with word replaced with x
        newline = splitline.replace(word,x)

        #the program should print the newline with word replaced with key
        print(newline)

似乎我不能使用 splitline.replace dict.keys(mydict),因为我假设它会选择所有的键,而不仅仅是实例我正在努力处理。有没有办法可以做到这一点?

It seems I can't use splitline.replace with dict.keys(mydict) as I assume that it will select all of the keys and not just the instance I am trying to deal with. Is there a way I can do this?

我希望我已经正确解释了自己。

I hope I've explained myself properly.

我不知道你为什么迭代每一个角色,每次分配 splitline 是一样的。我们不这样做。

I'm not sure why you're iterating over every character, assigning splitline to be the same thing every time. Let's not do that.

words = text.split()  # what's a splitline, anyway?

看起来你的术语倒退了,字典看起来像: {key:值} 不像 {value:key} 。在这种情况下:

It looks like your terminology is backwards, dictionaries look like: {key: value} not like {value: key}. In which case:

my_dict = {'the': 1, 'in': 2, 'a': 3}

是完美的转向男人住在房子里1人住2 3房

从那里你可以使用 dict.get 。我不推荐 str.replace

From there you can use dict.get. I don't recommend str.replace.

final_string = ' '.join(str(my_dict.get(word, word)) for word in words)
# join with spaces all the words, using the dictionary substitution if possible

dict.get 允许您指定默认值,如果该键不在字典中比起 dict [key] 提出一个 KeyError 。在这种情况下,您说的是给我键值,如果不存在,请给我

dict.get allows you to specify a default value if the key isn't in the dictionary (rather than raising a KeyError like dict[key]). In this case you're saying "Give me the value at key word, and if it doesn't exist just give me word"