- Machine Learning for Cybersecurity Cookbook
- Emmanuel Tsukerman
- 344字
- 2021-06-24 12:28:57
How to do it...
Let's see how to generate text using Markov chains by performing the following steps:
- Start by importing the markovify library and a text file whose style we would like to imitate:
import markovify
import pandas as pd
df = pd.read_csv("airport_reviews.csv")
As an illustration, I have chosen a collection of airport reviews as my text:
"The airport is certainly tiny! ..."
- Next, join the individual reviews into one large text string and build a Markov chain model using the airport review text:
from itertools import chain
N = 100
review_subset = df["content"][0:N]
text = "".join(chain.from_iterable(review_subset))
markov_chain_model = markovify.Text(text)
Behind the scenes, the library computes the transition word probabilities from the text.
- Generate five sentences using the Markov chain model:
for i in range(5):
print(markov_chain_model.make_sentence())
- Since we are using airport reviews, we will have the following as the output after executing the previous code:
Surprisingly realistic! Although the reviews would have to be filtered down to the best ones.
- Generate 3 sentences with a length of no more than 140 characters:
for i in range(3):
print(markov_chain_model.make_short_sentence(140))
With our running example, we will see the following output:
推薦閱讀
- 腦動力:C語言函數速查效率手冊
- 傳感器技術實驗教程
- ROS機器人編程與SLAM算法解析指南
- CorelDRAW X4中文版平面設計50例
- 高維聚類知識發現關鍵技術研究及應用
- Visual Basic.NET程序設計
- 新編計算機組裝與維修
- Microsoft System Center Confi guration Manager
- Unity Multiplayer Games
- Mastering Text Mining with R
- Mastering OpenStack(Second Edition)
- 樂高創意機器人教程(中級 上冊 10~16歲) (青少年iCAN+創新創意實踐指導叢書)
- Practical Network Automation
- Appcelerator Titanium Smartphone App Development Cookbook(Second Edition)
- Linux Administration Cookbook