【问题标题】:LZW Compression In LuaLua 中的 LZW 压缩
【发布时间】:2012-07-29 11:35:30
【问题描述】:

这是 Lempel-Ziv-Welch 压缩的伪代码。

 pattern = get input character
 while ( not end-of-file ) {
     K = get input character
     if ( <<pattern, K>> is NOT in 
             the string table ){
         output the code for pattern
         add <<pattern, K>> to the string table
         pattern = K
     }
     else { pattern = <<pattern, K>> }
 }
 output the code for pattern
 output EOF_CODE

我正在尝试在 Lua 中对此进行编码,但它并没有真正起作用。这是我在 Python 中的 LZW 函数后建模的代码,但在第 8 行出现“尝试调用字符串值”错误。

 function compress(uncompressed)

 local dict_size = 256
 local dictionary = {}

 w = ""
 result = {}
 for c in uncompressed do
  -- while c is in the function compress
     local wc = w + c
     if dictionary[wc] == true then
         w = wc
     else
         dictionary[w] = ""
         -- Add wc to the dictionary.
         dictionary[wc] = dict_size
         dict_size = dict_size + 1
         w = c
    end
 -- Output the code for w.
 if w then
   dictionary[w] = ""
 end
 end
 return dictionary
 end

 compressed = compress('TOBEORNOTTOBEORTOBEORNOT')
 print (compressed)

我真的很想得到一些帮助,让我的代码运行,或者帮助我在 Lua 中编写 LZW 压缩代码。非常感谢!

【问题讨论】:

标签: function dictionary lua compression lzw


【解决方案1】:

假设uncompressed 是一个字符串,你需要使用类似这样的东西来迭代它:

for i = 1, #uncompressed do
  local c = string.sub(uncompressed, i, i)
  -- etc
end   

第 10 行还有一个问题; .. 用于 Lua 中的字符串连接,所以这一行应该是 local wc = w .. c

您可能还想阅读this 以了解字符串连接的性能。长话短说,将每个元素保存在表格中并使用table.concat() 返回它通常更有效。

【讨论】:

  • 抱歉,我对这个很陌生...但是在 --etc 评论之后应该做什么?非常感谢!
  • 它运行没有错误!谢谢!我现在的小问题是它正在打印“table:0x7861e7f0”......谢谢!
  • 另外,我尝试将“返回字典”更改为“返回 w”,并将其移到 for 循环内,但现在它只打印“T”。
  • return table.concat(dictionary) 会将其输出为字符串。
  • 现在正在打印“”,什么都没有。
【解决方案2】:

您还应该看看here 以下载 Lua 中高性能 LZW 压缩算法的源代码...

【讨论】:

  • 啊,但它展示了一些不错的 Lua 技术,可能有用。
  • 还要注意它的许可证是 GPL 版本 2
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-09
  • 1970-01-01
  • 2022-08-18
相关资源
最近更新 更多