Python - A way to learn and detect text patterns?
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.
Introduction
In Python, the right way to detect text patterns depends on the kind of pattern you mean. If the rule is explicit, such as an email address or invoice number, regular expressions are usually the best tool. If the pattern must be learned from examples, use a text-processing pipeline and a model.
Start with Rule-Based Matching
For known text shapes, Python's re module is the fastest path. It lets you define patterns such as dates, order IDs, hashtags, or repeated word structures.
A simple example extracts invoice codes like INV-2026-1042:
Output:
This is ideal when the signal is structural. You know what the text should look like, and the program only needs to recognize it.
Use raw strings such as r"\d+" for regex patterns. That keeps backslashes readable and avoids accidental escaping mistakes.
Normalize Before Matching
Pattern detection gets more reliable when you clean the text first. Even a light preprocessing step can remove casing and punctuation differences that would otherwise hide the pattern.
Output:
This matters when your rules are concept-level rather than punctuation-level. For example, Disk full, disk FULL, and disk-full should often map to the same underlying message.
Learn Patterns from Labeled Examples
Regex works poorly when the wording varies too much. Suppose you want to classify support messages into categories such as billing, login, or shipping. In that case, you usually want a model that learns which words and phrases correlate with each label.
A small scikit-learn pipeline is enough for many practical tasks:
This kind of pipeline learns a statistical pattern from examples instead of relying on a hand-written rule. It is often the right answer when the same intent appears in many different phrasings.
Choosing Between Rules and Learning
A practical decision rule is simple:
- Use regex when the pattern has a stable shape.
- Use a learned model when wording varies but labels are known.
- Use both when structure and intent matter together.
For example, you might first extract product codes with regex and then feed the cleaned message into a classifier that predicts the request type.
You can combine both approaches cleanly:
After extracting the order ID, a separate model can classify the request as refund, replacement, or delivery issue.
Common Pitfalls
One common mistake is using regex for problems that are not actually pattern-shaped. If users can write the same idea in dozens of ways, the regular expression quickly becomes brittle and unreadable.
Another issue is training a model on too little or too noisy data. A classifier can only learn the patterns present in the examples you provide. If labels are inconsistent, the model will be inconsistent too.
A third problem is skipping preprocessing. Small differences in casing, punctuation, and whitespace often reduce match quality for both regex and learned models.
Finally, do not confuse detection with understanding. A pattern detector can find text that looks like an invoice number or predict that a sentence is about billing. That does not mean it fully understands the document. Keep the scope narrow and measurable.
Summary
- Use Python regex for explicit text shapes such as IDs, dates, and codes
- Normalize text before matching to improve consistency
- Use scikit-learn or another model when the pattern must be learned from examples
- Combine rule-based extraction with classification when both structure and intent matter
- Pick the simplest method that matches the problem instead of forcing machine learning everywhere
Related reading
- Python - Calculate Hierarchical clustering of word2vec vectors and plot the results as a dendrogram
- Python - How to intuit word from abbreviated text using NLP?
- Python NLP Intent Identification
- Python NLTK pos_tag not returning the correct part-of-speech tag
- Python - machine learning
- Python - sklearn How to pass parameters to the customize ModelTransformer class by gridsearchcv
- python - how to append numpy array to a pandas dataframe
- Python Convert timedelta to int in a dataframe
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.