ابتدا کتابخانه های مورد نظر را فراخوانی میکنیم:
import nltk
import urllib
import bs4 as bs
import re # regular expression
from nltk.corpus import stopwords
nltk.download('punkt')
سپس در کد زیر منبع دریافت داده را مشخص میکنیم:
#get the data source
#use url to read the context
source = urllib.request.urlopen('https://simple.wikipedia.org/wiki/Global_warming')
در کد زیر شی مربوط به beautiful را مشخص میکنیم و مشخص میکنیم که به چه روشی parse صورت گیرد:
# we need 2 parameter : 1: source 2: way of parsing
# creating beautiful soup object
soup=bs.BeautifulSoup(source,'lxml')
در کد زیر میخواهیم که هر پاراگراف خوانده شود و در متغیر text ذخیره شود:
text=""
for paragraph in soup.find_all('p'):
text+=paragraph.text
طول متن برابر با 10392 است. که بخشی از آن در تصویر زیر مشخص است:

با دستور زیر اعداد را حذف میکنیم و به جای آن ****** میگذاریم:
# preprocessing the data
# removing all the numbers and replace by ********
text1= re.sub(r'\[[0-9]*\]','******** ',text)
len(text1) #shorter lenght because numbers have been removed
با کد زیر فواصل اضافی را حذف میکنیم:
#remove additional spaces
text2=re.sub(r'\s+',' ',text1)
len(text2)
با کد زیر نیز حروف ها را به حروف کوچک تبدیل میکنیم:
text3_lower=text2.lower()
و در نهایت با کد زیر تمامی جملات را جدا میکنیم:
#converting to sentences
sentences=nltk.sent_tokenize(text3_lower)
len(sentences)
for i in sentences:
print(i)
print('----------------')