如何在Clojure中添加句子编号?

如何在Clojure中添加句子编号?,clojure,Clojure,我想在文本文件中添加句子编号: 把[1][2][3]。。。在每个句子前面 [1] Sentence one. [2] Sentence two. ... 一个句子以中的一个结尾 我不知道如何在Clojure中执行此操作。以下是我的尝试: (def text "Martin Luther King, Jr. I Have a Dream delivered 28 August 1963, at the Lincoln Memorial, Washington D.C. I am happ

我想在文本文件中添加句子编号: 把[1][2][3]。。。在每个句子前面

[1] Sentence one. [2] Sentence two. ...
一个句子以
中的一个结尾

我不知道如何在
Clojure中执行此操作。
以下是我的尝试:

(def text "Martin Luther King, Jr.

I Have a Dream

delivered 28 August 1963, at the Lincoln Memorial, Washington D.C.


I am happy to join with you today in what will go down in history as the greatest demonstration for freedom in the history of our nation.

Five score years ago, a great American, in whose symbolic shadow we stand today, signed the Emancipation Proclamation. This momentous decree came as a great beacon light of hope to millions of Negro slaves who had been seared in the flames of withering injustice. It came as a joyous daybreak to end the long night of their captivity.

But one hundred years later, the Negro still is not free. One hundred years later, the life of the Negro is still sadly crippled by the manacles of segregation and the chains of discrimination. One hundred years later, the Negro lives on a lonely island of poverty in the midst of a vast ocean of material prosperity. One hundred years later, the Negro is still languished in the corners of American society and finds himself an exile in his own land. And so we've come here today to dramatize a shameful condition.")
定义句子结尾:

(def sentence-ending #"[.!?]")
使用替换功能:

(require '[clojure.string :as str])
(str/replace text sentence-ending "[number]")   

我知道这在逻辑上是错误的!我把所有的
都换了。也许字符串替换不是正确的方法。如何解决这个问题?

你可以把
文本
分成句子序列。然后
将每个句子映射到
[number]
的前面,并再次将这些句子连接成一个字符串

(->> (clojure.string/split text #"[.?!]")       ; split text
     (map-indexed #(str "[" (inc %1) "] " %2))  ; prepend number
     (apply str))                               ; join to one string

但是,将文本拆分为字符串的条件很简单。如您所见,有些单词包含
,它们不是句子的结尾。你应该改进句子的终止条件。

获得完整句子(包括标点符号)的一种方法是对整个句子进行正则化并使用匹配器。我不知道这是不是最好的办法。但它是有效的

在那之后,我认为interleave可以很好地解决这类问题

(let [matcher (re-matcher #"[^.!?]*[.!?]" text)
      sentences (take-while seq (repeatedly #(re-find matcher)))
      numbers (map #(str "[" % "] ") (range))]
  (apply str (interleave numbers sentences)))

谢谢你的帮助。我不是要替换所有的
。我可怜的原始计划是错误的。我之所以使用替换表达式是因为我在那里被绊倒了。你的方法太棒了!因为我正在处理的文本文件的行结尾是
\r\n
。我将此添加到
重新匹配程序中
#“[^.!?]*[.!?][\r\n]*”
。但我不知道该怎么处理:1。类似华盛顿特区的缩写
2。冒号后面的句子和新行字符(
:\r\n
)应该是新句子。有什么提示来处理这个问题吗?我是一个编程新手,所以我的问题可能很幼稚或者很琐碎。谢谢你的回答,这很有启发性。