0

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)

2 Answers 2

1

No problem!

string1_words = set(string1.split())
string2_words = set(string2.split())
common_words = string1_words & string2_words
print(common_words)
Sign up to request clarification or add additional context in comments.

Comments

1

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".

1 Comment

It would be even better not to strip words, because it would only remove characters from the beginning and the end of the string, but to replace all unwanted characters, i.e.to leave only letters and digits: import re; preprared_string = re.sub(r'[^\w]+', ' ', original_string);. It would solve even more cases! For example, if someone forgot to put space in the middle of the word: "Hello!Nice to meet you, my friend!". Moreover, the solution would help to remove characters you did not specify at all! i.e. ':' or '\', or '-', and etc.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.