2010-03-31 3 views
6

에서 단어의 목록을 제거하는 방법 내가 (Clojure의에서)하고 싶으면 무엇 : 예를 들어문자열

, 나는 제거해야 할 단어의 벡터가 :

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

을 .. . 문자열의 벡터 :

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

그래서, 각각의 금지 된 단어가 각 문자열에서 제거해야하며, 그 결과는,이 경우에는 다음과 같습니다 [ "영화 목록" "thisisastring" "하하"].

어떻게 하시겠습니까? 대신

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

당신이 더 많은 '관용적'싶은 경우에, 당신은 clojure.contrib.string에서 replace-str을 사용할 수 있습니다 : 함수의 합성이 좋고 간단 할 수 -> 매크로를 사용

+0

이 링크가 도움이 : http://github.com/richhickey/clojure-contrib/blob/bacf49256673242bb7ce09b9f5983c27163e5bfc/src/main/clojure/clojure/contrib/string.clj#L162 –

답변

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)) 
+0

을 반환합니다. 입력 문자열에 대해 단일 패스 만 수행하기 때문에 더 좋아집니다. –

+0

아래의 귀하의 의견에 대해 [ "th :) e"]로 귀하의 답변을 시도해 보셨습니까? 그것을 시도하면 올바르게 작동하지 않습니다. –

+0

@ALevy 그는 나에게 예상대로 작동합니다. 입력 문자열에 나타나는 금지 단어 만 제거하고 [ "th :) e :") "] 출력합니다 ("the "":)). 금지 된 단어를 이미 제거했을 때 나타나는 금지 된 단어가 아닙니다. 내 솔루션은 반환 값이 금지 단어 벡터의 순서에 의존하지 않는 유일한 솔루션입니다. – cgrand

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)) 
+0

일 이후 이 작품. 최첨단에서 이것을 테스트하고 싶다면'clojure.contrib.str-utils'가 현재 소스에서'clojure.contrib.string'으로 이름이 바뀌었고're-gsub'는' 바꾸기 - 다시. 또한 다른 두 단어 사이에서 단어를 제거하는 것이 주변의 공백 하나를 제거해야하는 경우 (위의 코드처럼 아무 것도 아닌 경우) 문자열의 처음과 끝에있는 * 및 * 단어를 올바르게 처리해야합니다 , 좀 더 복잡한 정규 표현식 마법이 요구 될 것입니다. –

+0

'Pattern/compile'에 대한 호출은're-pattern'으로 대체 될 수 있습니다. –

+0

@Brian :'re-pattern'은 여기에 필요한'Pattern/LITERAL' 인자를 받아들이지 않습니다. –

0

#(.replace %1 s "")입니다.

정규식을 사용할 필요가 없습니다.

+1

모든 다중 응답은 본질적으로 깨졌습니다. (def forbidden-words [ ":)" "the" "." ","])))))))))))))))))))))))))))))))))))))))) ;; 이것은 ("") – cgrand