如何把一个句子中的所有单词都变成一个数字,而且还能把它变成b

2024-04-25 11:54:42 发布

您现在位置:Python中文网/ 问答频道 /正文

好的,我必须用python编写一个程序,这个程序能够为一个句子中的每个单词生成一个数字,如果这个单词是相同的,那么它将具有相同的数字,但是我也必须能够将它改回原来的句子。你知道吗

例如,“今天猫坐在垫子上”将更改为0 1 2 3 4 1 5

0是“今天”,5是“垫子”,1是“the”

所以基本上,如果我得到了这样一个想法,即为每个单词创建一个变量作为一个数字,唯一的问题是我不知道应该开始制作这个程序

如果您能帮忙,我们将不胜感激。谢谢:)


Tags: the程序数字单词句子垫子
1条回答
网友
1楼 · 发布于 2024-04-25 11:54:42

这听起来很像学校的作业。因为根据我的经验,我可以说最好的做法是自己动手,所以我建议只看我给出的提示,如果你真的卡住了,看看代码。你知道吗

提示1:

Separate the sentence into a list of words first.

你可以使用

words = sentence.split(" ")

提示2:

You want to create some kind of mapping from word to number, but also in reverse.

你可以使用

dicts. Treat them as literal dictionaries: Make one dict with the words as keys and the numbers as values, and one with numbers as keys and words as values. That'll allow you to look up numbers and words as necessary. Note that the dict which has numbers as keys could theoretically be a list, however this might break when you don't want numbers anymore, or when you want to delete certain entries.

提示3:

You'll need to generate an entry in both dicts mentioned in Hint 2 for every word - to make sure you can go back. Thus, a for loop over the list with words, and at every iteration generate an entry in both dicts.

提示4:

In order to make sure same words map to the same number, there are two ways to go. Firstly, during the iteration, you can simply check if the word is already in the words->numbers dict. If it is, skip it. Otherwise, generate the entries. Note that you need to keep track of the highest number you have used. Secondly, you could convert the list with words to a set. This will directly remove all duplicates, though you may lose the ordering of the words, meaning that in your example it might become 3 2 0 5 4 2 1

我希望这会有用。如果绝对必要的话,我可以提供代码来完成它,但是我强烈建议你自己去弄清楚。你知道吗

相关问题 更多 >