Home > Back-end >  Add prefixes to word groups in Python
Add prefixes to word groups in Python

Time:09-18

How can I add a prefix to each single word in a given word group using .join function?

:param vocab_words: list of vocabulary words with a prefix.
:return: str of prefix followed by vocabulary words with
prefix applied, separated by ' :: '.

This function takes a `vocab_words` list and returns a string
with the prefix  and the words with prefix applied, separated
 by ' :: '. "

I understand that prefix is always vocab_words[0] in the string.

I tried

 def make_word_groups(vocab_words):
    return ' :: ' .join(vocab_words[0] for i in vocab_words[0:])

It does not work. I am getting AssertionError. As a result - lot of prefixes and only then some words with prefixes.

CodePudding user response:

You can try this:

def make_word_groups(vocab_words):
    result_data = f'{vocab_words[0]} :: '
    result_data  = ' :: '.join([vocab_words[0]   word for word in vocab_words[1:]])
    return result_data

input_data = ['auto', 'didactic', 'graph', 'mate', 'chrome', 'centric', 'complete', 'echolalia', 'encoder', 'biography']
print(make_word_groups(input_data))
input_data = ['en' ,'circle', 'fold', 'close','joy', 'lighten', 'tangle', 'able', 'code', 'culture']
print(make_word_groups(input_data))
input_data = ['pre', 'serve', 'dispose', 'position', 'requisite', 'digest', 'natal', 'addressed', 'adolescent', 'assumption', 'mature', 'compute']
print(make_word_groups(input_data))

Output:

auto :: autodidactic :: autograph :: automate :: autochrome :: autocentric :: autocomplete :: autoecholalia :: autoencoder :: autobiography
en :: encircle :: enfold :: enclose :: enjoy :: enlighten :: entangle :: enable :: encode :: enculture
pre :: preserve :: predispose :: preposition :: prerequisite :: predigest :: prenatal :: preaddressed :: preadolescent :: preassumption :: premature :: precompute

CodePudding user response:

Try this:

def make_word_groups(vocab_words):
   separator = ' :: '

   prefix = vocab_words[0]
   words = vocab_words[1:]

   prefixed_words = [prefix   word for word in words]
   result = prefix   separator   separator.join(prefixed_words)

   return result
  • Related