【问题标题】:Reconstructing string of words using index position of words使用单词的索引位置重建单词字符串
【发布时间】:2017-03-20 16:50:47
【问题描述】:

我压缩了一个文件,它给字符串中的每个唯一单词一个值(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] ["Lines","long","lines","very","many","likes","for","i","love","how","amny","does"," it","take","to","make","a","cricle..","big","questions"]

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

原句是“Lines long lines very lines amny likes for lines i lovelines how many lines to make a cricle”

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

【问题讨论】:

  • 如何将数字映射到单词?
  • 如果你能分享示例 IO 会很有帮助
  • 请提供您愿意使用的示例和数据结构?

标签: python


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

    您可以使用 dict 或列表以及对 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 $ * / ... ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-09
      • 2017-10-21
      • 2015-05-15
      • 2016-02-21
      • 2016-12-26
      相关资源
      最近更新 更多