获取字符串中非唯一单词的边界索引



假设我有以下字符串:

 (def strg "apple orange apple")

我想要字符串中每个非唯一单词的边界索引。因此,苹果的第一次出现应该具有边界指数(0.4(,而苹果的第二次出现应该有边界指数(13,17(。

我一直在使用的一种方法是,首先将每个字符的索引存储在字符串中,然后,对于每个索引n,通过在n-1处寻找空间来识别单词边界(是的,这会错过字符串单词的开头(。如果满足了这个条件,则遍历接下来的k个字符,直到找到另一个空格——紧挨在该空格之前的位置上的字符是第二个边界索引。这个(失败的(代码的第一部分是

 (for [ch strg] 
      (let [indx  (int  (.indexOf  strg  (str ch)))] 
           (cond  (= (subs ch indx-1 ) " " ) 
           continue with rest of above-described code logic

任何想法(Clojure、Java或Python都可以(都将受到

的赞赏

Clojure/Java更典型的做法是使用起始字符和结束字符后的索引,因此使用[0, 5][13, 18]。Java的Matcher将以这种方式返回每个匹配的开始和结束。

(def strg "apple orange apple")
(defn re-indices [re s] 
  (let [m (re-matcher re s)] 
    ((fn step [] 
       (when (. m find) 
         (cons [(. m start) (. m end)] (lazy-seq (step))))))))
(re-indices #"S+" strg)
;=> ([0 5] [6 12] [13 18])

subs将适当地使用它们

(->> (re-indices #"S+" strg)
     (group-by (partial apply subs strg)))
;=> {"apple" [[0 5] [13 18]], "orange" [[6 12]]}

从这里,您只能筛选出那些具有多个索引对的子字符串键。

In [9]: import re
In [13]: def find_ind(word, s):
             return [(w.start(), w.end() - 1) for w in re.finditer(word, s) if s.count(word) > 1]
In [14]: find_ind("apple",s)
        [(0, 4), (13, 17)]
In [15]: find_ind("orange",s)
        []

使用python和re.finditer

返回一个迭代器,在字符串

中的RE模式的所有非重叠匹配中生成MatchObject实例

最新更新