Python for NLP
String, Regex, File handling — NLP engineer এর daily toolkit।
একজন chef এর জন্য ছুরি যেমন — একজন NLP engineer এর জন্য Python ঠিক তেমনই। আপনি কতটা ভাল NLP করতে পারবেন, সেটা অনেকটাই depend করে — আপনি কতটা smoothly Python দিয়ে text manipulate করতে পারেন তার উপর।
NLP এর জন্য Python এর তিনটা core skill খুব গুরুত্বপূর্ণ: (১) String manipulation — text কে কাটাছেঁড়া, খোঁজা, replace করা। (২) Regular Expressions (Regex) — pattern দিয়ে text এ specific structure খুঁজে বের করা। (৩) File handling — disk থেকে text data পড়া এবং লেখা।
String হলো আপনার কাঁচামাল। Regex হলো আপনার microscope — pattern খোঁজার যাদুর কাঁচ। File handling হলো আপনার গুদাম — যেখান থেকে data আসবে এবং যেখানে result যাবে। এই তিনটা একসাথে = NLP এর daily workflow।
import re
# 1. String operations
text = " Bangla NLP is Amazing! "
print(text.strip()) # remove spaces
print(text.lower()) # lowercase
print(text.replace("Amazing", "Powerful"))
print(text.split()) # tokenize by space
# 2. String slicing
sentence = "Natural Language Processing"
print(sentence[:7]) # 'Natural'
print(sentence[-10:]) # 'Processing'
# 3. Regex: find all emails in a text
sample = "Contact: sadiq@example.com or admin@nlp.io for help."
emails = re.findall(r"[\w\.-]+@[\w\.-]+", sample)
print("Emails:", emails)
# 4. Regex: clean text — keep only letters and spaces
dirty = "Hello!!! 1234 World??? #NLP @AI"
clean = re.sub(r"[^a-zA-Z\s]", "", dirty)
print("Clean:", clean.strip())
# 5. File handling (read a text file safely)
# with open("data.txt", "r", encoding="utf-8") as f:
# content = f.read()
# print("Total chars:", len(content))
# Writing a file
with open("output.txt", "w", encoding="utf-8") as f:
f.write("My first NLP output\n")
f.write("Bangla NLP is the future.")এই code এ তিনটা skill এক সাথে দেখানো হয়েছে। String operations দিয়ে আমরা text কে clean করছি। Regex (re module) দিয়ে email pattern খুঁজে বের করছি এবং unwanted character remove করছি। File handling এ আমরা সবসময় `with open()` use করি — কারণ এটা automatically file close করে দেয়, error হলেও। `encoding="utf-8"` খুব জরুরি — বিশেষ করে বাংলা text এর জন্য, নাহলে garbage character আসবে।
একটা reusable function `clean_text(text)` লিখুন যেটা: (১) lowercase করবে, (২) extra whitespace remove করবে, (৩) URL remove করবে (regex দিয়ে), (৪) email remove করবে, (৫) special character remove করবে, এবং (৬) cleaned text return করবে। এরপর এটা দিয়ে একটা .txt file এর সব line clean করে নতুন file এ save করুন। এই function পরে সব NLP project এ কাজে লাগবে।