【问题标题】:Regex pattern to count lines in poems with randomly \n or \n\n as line breaks正则表达式模式以随机 \n 或 \n\n 作为换行符来计算诗歌中的行数
【发布时间】:2020-12-15 11:05:56
【问题描述】:

我需要数一下 221 首诗的行数,并试着数一下换行符\n。

但是,有些行有双换行符 \n\n 以构成新的诗句。这些我只想算一个。每首诗中双换行符的数量和位置是随机的。

最小的工作示例:

library("quanteda")

poem1 <- "This is a line\nThis is a line\n\nAnother line\n\nAnd another one\nThis is the last one"
poem2 <- "Some poetry\n\nMore poetic stuff\nAnother very poetic line\n\nThis is the last line of the poem"

poems <- quanteda::corpus(poem1, poem2)

poem1 的结果行数应该是 5 行,poem2 应该是 4 行。

我试过stringi::stri_count_fixed(texts(poems), pattern = "\n"),但正则表达式模式不够精细,无法解决随机双换行问题。

【问题讨论】:

  • 不,使用"\\R+",它将任何一个或多个换行序列匹配为一个匹配。
  • 但是\n\n应该只算一个
  • 但是您不应该将_fixed 函数与正则表达式一起使用。应该是stringi::stri_count_regex。或stringr::str_count

标签: r regex nlp data-science quanteda


【解决方案1】:

您可以使用stringr::str_count\R+ 模式在字符串中查找连续换行序列的数量

> poem1 <- "This is a line\nThis is a line\n\nAnother line\n\nAnd another one\nThis is the last one"
> poem2 <- "Some poetry\n\nMore poetic stuff\nAnother very poetic line\n\nThis is the last line of the poem"
> library(stringr)
> str_count(poem1, "\\R+")
[1] 4
> str_count(poem2, "\\R+")
[1] 3

所以行数str_count(x, "\\R+") + 1

\R 模式匹配任何换行序列、CRLF、LF 或 CR。 \R+ 匹配一个或多个这样的换行序列。

R code DEMO online

poem1 <- "This is a line\nThis is a line\n\nAnother line\n\nAnd another one\nThis is the last one"
poem2 <- "Some poetry\n\nMore poetic stuff\nAnother very poetic line\n\nThis is the last line of the poem"
library(stringr)
str_count(poem1, "\\R+")
# => [1] 4
str_count(poem2, "\\R+")
# => [1] 3
## Line counts:
str_count(poem1, "\\R+") + 1
# => [1] 5
str_count(poem2, "\\R+") + 1
# => [1] 4

【讨论】:

  • 感谢您解释答案背后的理由,我很高兴了解与 \R 匹配的换行符。
猜你喜欢
  • 1970-01-01
  • 2011-12-31
  • 2010-09-07
  • 1970-01-01
  • 2021-06-05
  • 1970-01-01
  • 2010-11-13
  • 1970-01-01
相关资源
最近更新 更多