Lua中LZW压缩如何实现长尾词的压缩?

2026-04-01 18:551阅读0评论SEO资讯
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计429个文字,预计阅读时间需要2分钟。

Lua中LZW压缩如何实现长尾词的压缩?

这是一个关于Lempel-Ziv-Welch(LZW)压缩算法的伪代码片段的简化版本:

读取输入字符,直到文件结束初始化模式(pattern)初始化字符串表

while 文件未结束: 获取输入字符(pattern) 如果 pattern 和字符 K 不在字符串表中: 输出模式对应的代码 将模式 pattern 和字符 K 添加到字符串表 更新模式 pattern

这是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压缩.非常感谢!

Lua中LZW压缩如何实现长尾词的压缩?

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

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

第10行还有另一个问题; ..用于Lua中的字符串连接,因此该行应该是本地的wc = w .. c.

您可能还希望阅读this关于字符串连接的性能.简而言之,将每个元素保存在表中并使用table.concat()返回它通常更有效.

本文共计429个文字,预计阅读时间需要2分钟。

Lua中LZW压缩如何实现长尾词的压缩?

这是一个关于Lempel-Ziv-Welch(LZW)压缩算法的伪代码片段的简化版本:

读取输入字符,直到文件结束初始化模式(pattern)初始化字符串表

while 文件未结束: 获取输入字符(pattern) 如果 pattern 和字符 K 不在字符串表中: 输出模式对应的代码 将模式 pattern 和字符 K 添加到字符串表 更新模式 pattern

这是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压缩.非常感谢!

Lua中LZW压缩如何实现长尾词的压缩?

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

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

第10行还有另一个问题; ..用于Lua中的字符串连接,因此该行应该是本地的wc = w .. c.

您可能还希望阅读this关于字符串连接的性能.简而言之,将每个元素保存在表中并使用table.concat()返回它通常更有效.