Lua - 移除不在列表中的单词

我想从一个字符串中删除不在列表中的单词。

例如,我有字符串“我喜欢馅饼和蛋糕”或“ 馅饼和蛋糕很好吃”,我想删除不是“ 馅饼”或“ 蛋糕”的单词,最终得到一个字符串“ 馅饼蛋糕”。

如果不删除的单词可以从表中加载,那就太好了。

点赞
用户2198692
用户2198692
## 将下面翻译成中文并且保留原本的 markdown 格式

local function stripwords(inputstring, inputtable) local retstring = {} local itemno = 1; for w in string.gmatch(inputstring, "%a+") do if inputtable[w] then retstring[itemno] = w itemno = itemno + 1 end end

return table.concat(retstring, " ") end

```

只有当你想保留的单词是inputtable中的键才能使用此函数。该函数用于从inputstring中提取保留单词后的字符串,并返回一个包含保留单词的字符串。

2013-05-11 22:36:41
用户107090
用户107090

下面是另一种解决方案,但你可能需要裁剪结果中的最后一个空格。

acceptable = { "pie", "cake" }
for k,v in ipairs(acceptable) do acceptable[v]=v.." " end
setmetatable(acceptable,{__index= function () return "" end})

function strip(s,t)
    s=s.." "
    print('"'..s:gsub("(%a+) %s*",t)..'"')
end

strip("i like pie and cake",acceptable)
strip("pie and cake is good",acceptable)

gsub 是关键点。还有其他变体使用 gsub 和函数,而不是为 acceptable 设置元表。

2013-05-12 00:23:21
用户1244588
用户1244588

以下还实现了请求的最后一部分(希望这样):

如果未删除的单词可以从表中加载,那就太好了。

function stripwords(str, words)
    local w = {};
    return str:gsub("([^%s.,!?]+)%s*", function(word)
        if words[word] then return "" end
        w[#w+1] = word
    end), w;
end

请记住,Lua的模式匹配器与多字节字符串不兼容。这就是为什么我使用了上面的模式。如果您不关心多字节字符串,可以使用类似“(%a +)%s”的东西。在这种情况下,我还会通过string.upper运行单词。

测试/用法

local blacklist = { some = true, are = true, less = true, politics = true }
print((stripwords("There are some nasty words in here!", blacklist)))

local r, t = stripwords("some more are in politics here!", blacklist);
print(r);
for k,v in pairs(t) do
    print(k, v);
end
2013-05-13 12:59:49