Home>

I'm trying to determine if a sentence contains the specified word in Python
For example, in the following case, only cool is included and I want to display it.

text = "The T-shirt looks cool."
words = ['T','shirt','cool','l']

In the case of this example, only "cool" is an exact match, but a partially matching word is also returned.

T
shirt
cool
l
Corresponding source code
text = "The T-shirt looks cool."
words = ['T','shirt','cool','l']
for i in range (len (words)):
    if words [i] in text:
        print (words [i])
#output
T
shirt
cool
l
What I tried

I also tried putting spaces before and after the specified word, but the result did not change.
if'' + words [i] +'' in text:

text = "The T-shirt looks cool."
words = ['T','shirt','cool','l']
for i in range (len (words)):
    if'' + words [i] +'' in text:
        print (words [i])
#output
T
shirt
cool
l
Supplementary information (FW/tool version, etc.)

python 3.7.4

  • Answer # 1

    Perhaps what the questioner wants to do is "find an exact match between the words in the string and the words in the pre-specified word list."

    StringsplitDivide it into words with, and then remove the disturbing letters at both ends of each word.stripRemove with

    Display any pre-specified word list elements in the split words

    text = "The T-shirt looks cool."
    words = ['T','shirt','cool','l']
    splitted = list (map (lambda x: x.strip ('.,!?'), Text.split ()))
    print (splitted)
    for word in words:
        if word in splitted:
            print (word)
    ['The','T-shirt','looks','cool']
    cool

  • Answer # 2

    if words [i] in text:

    if words [i] == text:
    Please

    Compare strings in Python (exact match, partial match, magnitude relation, etc.) | note.nkmk.me