There's the case where you'd like to exclude words using a predefined list. Sample_text = "Sample text 123 !!!! Haha. In cases where you want to remove all characters except letters and numbers, you can use a regular expression. Remove all special characters and punctuation # After: Sample text with numbers and words # Before: Sample text with numbers 123455 and words !!! Here's how you use it: sample_text = "Sample text with numbers 123455 and words !!!" isalpha() method of Python strings will come in handy in those cases. Sometimes, you'd like to remove non-alphabetic characters like numbers or punctuation. # After: I want to keep this one: 10/10/20 but not this one # Before: I want to keep this one: 10/10/20 but not this one 222333 isdigit() method of strings: sample_text = "I want to keep this one: 10/10/20 but not this one 222333"Ĭlean_text = " ".join() # Side effect: removes extra spaces Using a regular expression gets a bit trickier. For instance, when you want to remove numbers but not dates. There are cases where you might want to remove digits instead of any number. But don't remove this one H2O"Ĭlean_text = re.sub(r"\b+\b\s*", "", sample_text)
You can use a regular expression for that: import re In some cases, you might want to remove numbers from text, when you don't feel they're very informative. "Yes, you got it right!\n This one too\n"
"This TEXT needs \t\t\tsome cleaning!!!.", Take a look at the example below: import re If you're using pandas, you can apply that function to a specific column using the. Then, you can use that function for pre-processing or tokenizing text. I'd recommend you combine the snippets you need into a function. Then, you can check the snippets on your own and take the ones you need.
#NLTK CLEAN TEXT HOW TO#
In the next section, you can see an example of how to use the code snippets. They're based on a mix of Stack Overflow answers, books, and my experience. I'll continue adding new ones whenever I find something useful.
This article contains 20 code snippets you can use to clean and tokenize text using Python.