Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

342
Vistas
How to find and count all repeating 2/3/4 word phrases

I've been trying to parse 300-400 word pieces of text and get all repeating 2/3/4 word phrases and I can't figure out the solution.

With one word commonalities I simply .split the text, .each_slice 1, then .map and .tally.

But with 2+ words, .each_slice doesn't work since I can't account for order.. For example the text is:

An alligator walked and an alligator walked alone.

It's gonna split to:

The alligator | walked and | another alligator | walked alone

What can I code to recognize that "alligator walked" repeats itself?

The only solution I can think of is removing the first word each time, that way the pair is gonna change constantly and get all options, but that seems awfully stupid..

Any help is appreciated!

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

The method you are looking for is Enumerable#each_cons, not Enumerable#each_slice.

I don't know exactly what your current solution looks like (it would have been better to share your actual code instead of a loose description of your code: "I simply .split the text, .each_slice 1, then .map and .tally"!), but for example you could do something like:

input = "An alligator walked and an alligator walked alone"

input.split(' ').map(&:downcase).each_cons(2).tally
# => {
#   ["an", "alligator"]=>2,
#   ["alligator", "walked"]=>2,
#   ["walked", "and"]=>1,
#   ["and", "an"]=>1,
#   ["walked", "alone"]=>1
#  }
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda