Text generator | Python

Nao Kawakami
2 min readDec 31, 2020

Summary

Automatically generate texts using Python, transformer.pipeline.

Modules

This is all modules I need for text generator.

from transformers import pipeline

Instantiate

# Argument must be `text-generation`
text_generator = pipeline("text-generation")

Generate texts

# Give a phrase that related to texts you want to generate
text_generator('I would like to')

Result

[{'generated_text': 'I would like to go back to the beginning where I was before the war, I wouldn\'t really have had them."\n\nIn their time at the helm, British command staffs and civilians were often caught up in the fray, fighting like bandits'}]

So cool! This starts with I would like to which is a phrase I feed to the model. Let’s run again!

Result

[{'generated_text': "I would like to thank the following people for their support in making this possible:\n\nDavid Wintour; Paul Tippett; Tony Blair; John Key; Simon Cameron (BBC); Mark Reckless, Mark Reckless's chief of staff"}]

I got new texts. This always return texts which start with I would like to. Are you curious of using other phrase? So do I.

Generate texts

# You want muscle
text_generator('muscle')

Result

[{'generated_text': 'muscle function to perform the right exercise. This exercise is called sprinting. It is the best exercise to perform during your cycling cycle, in fact. This time period has been measured by various measurements, including the distance at the end of the cycling'}]

This includes exercise and cycling. I believe this generates texts which are related to the given word. And it always starts with the given phrase.

Let’s try another one.

Generate texts

# Ask machine for an advice
text_generator('Does he like me?')

Result

[{'generated_text': "Does he like me? Is he interested in me? I don't know, but it is always nice to get a chance to share a feeling with one another.\n\nI did not ask him which I want to be next. My head is"}]

Awesome! This is pretty natural and could be on Twitter.

--

--