I want to check whether a particular string is present in a sentence. I am using simple code for this purpose
subStr = 'joker'
Sent = 'Hello World I am Joker'
if subStr.lower() in Sent.lower():
print('found')
This is an easy straightforward approach, but it fails when sentence appears as
hello world I am Jo ker
hello world I am J oker
As I am parsing sentence from a PDF
file some unnecessary spaces are coming here and there.
A simple approach to tackle this issue would be to remove all the spaces from a sentence and look for a substring match. I want to know other peoples thoughts on this, should I stick with this approach or look for some other alternatives.
There are three ways to compare String in Java: By Using equals() Method. By Using == Operator. By compareTo() Method.
If you have the string: string sample = "If you know what's good for you, you'll shut the door!"; And you want to find where it is in a sentence, you can use the IndexOf method. A non -1 answer means the string has been located.
Python Code: import re def text_match(text): patterns = '^\w+' if re.search(patterns, text): return 'Found a match!' else: return('Not matched!') print(text_match("The quick brown fox jumps over the lazy dog.")) print(text_match(" The quick brown fox jumps over the lazy dog. "))
My sentence must start with either one or more whitespaces/tabs. (tabs and spaces can be bunched together before any non-whitespace phrase of characters appears). Each word after the first must be separated by a whitespace. And yes, the sentence must end with a punctuation.
This is more efficient than replace
for small strings, more expensive for large strings. It won't deal with ambiguous cases, e.g. 'to day' vs 'today'.
subStr in ''.join(Sent.split()).lower() # True
you can use regular expression:
import re
word_pattern = re.compile(r'j\s*o\s*k\s*e\s*r', re.I)
sent = 'Hello World I am Joker'
if word_pattern.search(sent):
print('found')
I hope this works
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With