Home > Blockchain >  Check if different word combinations exist in text using Python
Check if different word combinations exist in text using Python

Time:11-15

I want to write a function that finds certain word combinations in text and tells it belongs to which list. Example:

my_list1 = ["Peter Parker", "Eddie Brock"]
my_list2 = ["Harry Potter", "Severus Snape", "Dumbledore"]

Example input: "Harry Potter was very sad"
Example output: my_list1

CodePudding user response:

You could iterate over the string and then append the occuring words into a list and then check for which words occur most to determine which list the whole string belongs to:

my_list1 = ["Peter Parker", "Eddie Brock"]
my_list2 = ["Harry Potter", "Severus Snape", "Dumbledore"]


to_check = "Harry Potter was very sad"

def which_list(to_check):
    belong_l1 = 0
    belong_l2 = 0    
    for i in to_check:
        if i in my_list1:
            belong_l1  = 1
        elif i in my_list2:
            belong_l2  = 1
    if belong_l1 > belong_l2:
        print("string belongs to list 1")
    elif belong_l1 < belong_l2:
        print("string belongs to list 2")
    else:
        print("belonging couldn't be determined")
        

CodePudding user response:

First, I would include the name in the list.

lst = (
          ("list1", ("Peter Parker", "Eddie Brock")),
          ("list2", ("Harry Potter", "Severus Snape", "Dumbledore")),
          ("list3", ("Harry Potter",)),
        )
while True:
  txt = input( "Enter some text: ")
  if len(txt) == 0: break
  for names in lst:
    for name in names[1]:
      if name in txt:
        print( f"'{name}' found in {names[0]}.")

And the result:

Enter some text: Harry Potter was here
'Harry Potter' found in list2.
'Harry Potter' found in list3.
Enter some text: Harry Potter and Dumbledore were here
'Harry Potter' found in list2.
'Dumbledore' found in list2.
'Harry Potter' found in list3.
  • Related