繁体   English   中英

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

[英]Get bounding indices of non-unique words in a string

假设我有以下字符串:

 (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实例

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM