2

リストにない単語を文字列から削除したい。

たとえば、「私はパイとケーキが好き」または「パイとケーキは良い」という文字列があり、「パイ」または「ケーキ」ではない単語を削除して、「パイ ケーキ」という文字列で終わるようにしたいとします。

削除されない単語をテーブルからロードできれば、それは素晴らしいことです。

4

3 に答える 3

4

別の解決策を次に示しますが、結果の最後のスペースを削除する必要がある場合があります。

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-12T00:23:21.453 に答える
0

以下は、リクエストの最後の部分も実装します(願っています):

削除されない単語をテーブルからロードできれば、それは素晴らしいことです。

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-13T12:59:49.037 に答える