使用单词的索引位置重构单词串

时间:2017-03-20 16:50:48

标签: python

我压缩了一个文件,它为我的字符串中的每个唯一单词赋予了一个值(0,1,2,3等)

我现在按照出现的顺序列出数字列表,例如(0,1,2,1,3,4,5,2,2等)

使用数字和唯一单词列表有没有办法解压缩句子并得到我开始的原始句子?

我有一个包含以下内容的文本文件

[0,1,2,3,2,4,5,6,2,7,8,2,9,2,11,12,13,15,16,17,18,19] ["行""长""线""非常""许多""喜欢""对于"" I""爱""如何"" amny&#34 ;, "不""它""取""至""使""& #34;" cricle ..""大""问题"]

我的代码通过获取位置和唯一单词来压缩orignal句子。

原来的句子是"线条长线非常线条amny喜欢线条我喜欢线条需要多少条线来制作一个cricle"

现在我希望能够使用唯一单词列表和位置列表重建句子。我希望能够用任何句子而不仅仅是这一句话来做到这一点。

2 个答案:

答案 0 :(得分:0)

要返回单词,您可以访问您的单词地图,并为每个数字在句子上添加单词。

numbers = [1, 2]
sentence = ""
words = {1: "hello", 2: "world"}
for number in numbers:
    sentence += words[number] + " "

sentence = sentence[:-1] # removes last space

答案 1 :(得分:0)

您可以使用词典或列表以及对str.join的理解:

words = ["I", "like", "boat", "sun", "forest", "dog"]
other_words = {0: "Okay", 1: "Example", 2: "...", 3: "$", 4:"*", 5: "/"}
sentence = (0,1,2,1,3,4,5,2,2)

print(" ".join(words[i] for i in sentence))
# I like boat like sun forest dog boat boat
print(" ".join(other_words[i] for i in sentence))
# Okay Example ... Example $ * / ... ...
相关问题