Syed Muhammad Ibrahim
Syed Muhammad Ibrahim

Reputation: 137

How to compare each word of a string with another string. Python

I'm new to python and I'm really struggling with this issue. I want to find whether a certain word from string1 exists in string2. And I need to compare each word of string1 with string2?

count  = len(string2.split())
print(count)
c=0
string1 = "I had a nice day. Infact, I had a great day! Yes sir."
string2 = "nice great sir day lol"

count  = len(string2.split())
print(count)
c=0

i =1
while i<=count:

  if string2[i].split(" ") in string1.split(" "):
    c+= 1
  i += 1

print(c)

Upvotes: 0

Views: 3425

Answers (2)

Spencer Stream
Spencer Stream

Reputation: 616

Abzac's answer works for any words that match exactly. For your input:

string1 = "I had a nice day. Infact, I had a great day! Yes sir."
string2 = "nice great sir day lol"

The resulting matching words will be

{'nice', 'great'}

You may want to strip punctuation or extra characters. If instead you use the code:

string1_words = set(string1.split())
string2_words = set(string2.split())

# Any characters you want to ignore when comparing
unwanted_characters = ".,!?"

string1_words = {word.strip(unwanted_characters) for word in string1_words}
string2_words = {word.strip(unwanted_characters) for word in string2_words}
common_words = string1_words & string2_words
print(common_words)

You will get the matching words as

{'nice', 'great', 'day', 'sir'}

One step further, you can ignore case as well using:

string1_words = {word.strip(unwanted_characters).lower() for word in string1_words}

This would match "Wow!" with "wow".

Upvotes: 1

Abzac
Abzac

Reputation: 2651

No problem!

string1_words = set(string1.split())
string2_words = set(string2.split())
common_words = string1_words & string2_words
print(common_words)

Upvotes: 1

Related Questions