【问题标题】:How to remove list of words from strings如何从字符串中删除单词列表
【发布时间】:2011-02-02 23:08:35
【问题描述】:

我想做的事(在 Clojure 中):

例如,我有一个需要删除的单词向量:

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

... 和一个字符串向量:

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

因此,应该从每个字符串中删除每个禁用词,在这种情况下,结果将是:[“movie list”“thisisastring”“haha”]。

如何做到这一点?

【问题讨论】:

标签: string clojure stop-words


【解决方案1】:
(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))

【讨论】:

  • 我更喜欢这个,因为它只对输入字符串进行一次传递。
  • 关于您在下面的评论,您是否尝试过自己的答案 ["th:)e"] ?当我尝试它时它不能正常工作。
  • @ALevy 对我来说,他按预期工作:对于 ["th:)e" ":the)"] 它输出 ("the" ":)") 仅删除出现的禁用词在输入字符串中 - 而不是在您已经删除其他禁用词时出现的禁用词。我的解决方案是唯一一个返回值不依赖于禁用词向量的顺序的解决方案。
  • 我最喜欢这个解决方案,因为它不使用循环,而且速度很快。
【解决方案2】:
(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))

【讨论】:

  • +1,因为这行得通。对于那些想在最前沿进行测试的人,请注意clojure.contrib.str-utils 在当前来源中已重命名为clojure.contrib.stringre-gsub 已成为replace-re。另请注意,如果从其他两个单词之间删除一个单词应该需要删除它周围的一个空格(而不是像上面的代码那样没有)字符串开头和结尾的单词要正确处理,则需要更多涉及的正则表达式魔术。
  • 您对Pattern/compile 的调用可以替换为re-pattern
  • @Brian: re-pattern 不接受此处必需的 Pattern/LITERAL 参数。
  • 所有多遍答案都有错误,请尝试输入 ["th:)e"] 的解决方案。
【解决方案3】:

使用函数组合和-> 宏可以很简单:

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

如果您想更“惯用”,可以使用 clojure.contrib.string 中的 replace-str,而不是 #(.replace %1 s "")

这里不需要使用正则表达式。

【讨论】:

  • 所有多遍答案本质上都被破坏了:(def 禁止单词 [":)" "the" "." ","]) (for [s [":the)"]] (-> s ((apply comp (for [s disabled-words] #(.replace %1 s "")))))) ;;这将返回 ("")
猜你喜欢
  • 2011-03-31
  • 1970-01-01
  • 1970-01-01
  • 2023-02-02
  • 1970-01-01
  • 2015-01-02
  • 2014-11-21
  • 1970-01-01
相关资源
最近更新 更多