6

私がやりたいこと(Clojureで):

たとえば、削除する必要のある単語のベクトルがあります。

(def forbidden-words [":)" "the" "." "," " " ...many more...])

...そして文字列のベクトル:

(def strings ["the movie list" "this.is.a.string" "haha :)" ...many more...])

したがって、禁止されている各単語を各文字列から削除する必要があります。この場合、結果は["movie list""thisisastring""haha"]になります。

これを行う方法 ?

4

3 に答える 3

7
(def forbidden-words [":)" "the" "." ","])
(def strings ["the movie list" "this.is.a.string" "haha :)"])
(let [pattern (->> forbidden-words (map #(java.util.regex.Pattern/quote %)) 
                (interpose \|)  (apply str))]
  (map #(.replaceAll % pattern "") strings))
于 2010-04-01T07:17:41.567 に答える
1
(use 'clojure.contrib.str-utils)
(import 'java.util.regex.Pattern)
(def forbidden-words [":)" "the" "." "," " "])
(def strings ["the movie list" "this.is.a.string" "haha :)"])
(def regexes (map #(Pattern/compile % Pattern/LITERAL) forbidden-words))
(for [s strings] (reduce #(re-gsub %2 "" %1) s regexes))
于 2010-03-31T17:48:47.887 に答える
0

関数構成と->マクロを使用すると、これは素晴らしく簡単になります。

(for [s strings] 
  (-> s ((apply comp 
           (for [s forbidden-words] #(.replace %1 s ""))))))

より「慣用的」になりたい場合はreplace-str、 の代わりに from clojure.contrib.stringを使用できます#(.replace %1 s "")

ここで正規表現を使用する必要はありません。

于 2010-03-31T21:47:21.310 に答える