scala-regexp: разбить строку на массив из двух следующих слов - PullRequest
0 голосов
/ 28 апреля 2018

Мне нужно разбить строку на массив с элементами в виде двух следующих слов по scala:

"Hello, it is useless text. Hope you can help me."

Результат:

[[it is], [is useless], [useless text], [Hope you], [you can], [can help], [help me]]

Еще один пример:

"This is example 2. Just\nskip it."

Результат: [[This is], [is example], [Just skip], [skip it]]

Я попробовал это регулярное выражение:

var num = """[a-zA-Z]+\s[a-zA-Z]+""".r

Но вывод:

scala> for (m <- re.findAllIn("Hello, it is useless text. Hope you can help me.")) println(m)
it is
useless text
Hope you
can help

Так что он игнорирует некоторые случаи.

Ответы [ 4 ]

0 голосов
/ 30 апреля 2018

Вам нужно использовать split, чтобы разбить строку на слова, разделенные несловесными символами, а затем sliding, чтобы сложить слова так, как вы хотите;

val text = "Hello, it is useless text. Hope you can help me."

text.trim.split("\\W+").sliding(2)

Вы также можете удалить escape-символы, как описано в других ответах.

0 голосов
/ 28 апреля 2018

Сначала разделите знаки пунктуации и цифры, затем разделите их пробелами, затем просмотрите результаты.

def doubleUp(txt :String) :Array[Array[String]] =
  txt.split("[.,;:\\d]+")
     .flatMap(_.trim.split("\\s+").sliding(2))
     .filter(_.length > 1)

использование:

val txt1 = "Hello, it is useless text. Hope you can help me."
doubleUp(txt1)
//res0: Array[Array[String]] = Array(Array(it, is), Array(is, useless), Array(useless, text), Array(Hope, you), Array(you, can), Array(can, help), Array(help, me))

val txt2 = "This is example 2. Just\nskip it."
doubleUp(txt2)
//res1: Array[Array[String]] = Array(Array(This, is), Array(is, example), Array(Just, skip), Array(skip, it))
0 голосов
/ 28 апреля 2018

Сначала обработайте string как есть, удалив все escape-символы.

scala> val string = "Hello, it is useless text. Hope you can help me."
val preprocessed = StringContext.processEscapes(string)
//preprocessed: String = Hello, it is useless text. Hope you can help me.

OR

scala>val string = "This is example 2. Just\nskip it."
val preprocessed = StringContext.processEscapes(string)
//preprocessed: String =
//This is example 2. Just
//skip it.

Затем отфильтруйте все необходимые символы (например, символы, пробелы и т. Д.) И используйте функцию slide как

val result = preprocessed.split("\\s").filter(e => !e.isEmpty && !e.matches("(?<=^|\\s)[A-Za-z]+\\p{Punct}(?=\\s|$)") ).sliding(2).toList

//scala> res9: List[Array[String]] = List(Array(it, is), Array(is, useless), Array(useless, Hope), Array(Hope, you), Array(you, can), Array(can, help))
0 голосов
/ 28 апреля 2018

Извините, я знаю только Python. Я слышал, что два почти одинаковы. Надеюсь, вы понимаете

string = "it is useless text. Hope you can help me."

split = string.split(' ')  // splits on space (you can use regex for this)

result = []

no = 0

count = len(split)

for x in range(count):
    no +=1

    if no < count:

        pair = split[x] + ' ' + split[no]   // Adds the current to the next

        result.append(pair)

Вывод будет:

['it is', 'is useless', 'useless text.', 'text. Hope', 'Hope you', 'you can', 'can help', 'help me.']
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...