vendredi 19 juin 2020

Join strings, but it shouldn't exceed the character limit

For some NLP task, I need to join a variable number of random words into a longer string. For instance:

from random import choices

options = ['dolphin', 'dog', 'platypus', 'monkey', 'sloth', 'butterfly']

' '.join(choices(options, k=3))
'dolphin platypus sloth'

No matter the number of randomly selected words, the length of the resulting string should not exceed 30, and the words should not be partial. I will need to pad the string until it has length 3 if the randomly selected word wouldn't fit below 30.

What can I do? I'm mainly looking for a one-liner, I'm not a fan of for loops and it's more difficult to integrate it to a Tensorflow pipeline.




Aucun commentaire:

Enregistrer un commentaire