Python program to extract Keywords from a list

Python program to extract Keywords from a list

In this tutorial, we'll extract keywords from a list. The term "keyword" can be a bit ambiguous, but for the purposes of this tutorial, we'll assume that a keyword is any word that is part of a predefined list of common keywords.

Objective:

Given a list of strings, extract those strings that are present in a predefined set of keywords.

Example:

For the list of strings:

['apple', 'for', 'banana', 'while', 'cherry', 'loop'] 

and the predefined set of keywords:

{'for', 'while', 'if', 'else'} 

The result will be:

['for', 'while'] 

Python Program:

def extract_keywords_from_list(string_list, keywords): # Use list comprehension to filter strings that are also in the set of keywords return [word for word in string_list if word in keywords] # Test the function sample_list = ['apple', 'for', 'banana', 'while', 'cherry', 'loop'] predefined_keywords = {'for', 'while', 'if', 'else'} result = extract_keywords_from_list(sample_list, predefined_keywords) # Print the results print(f"Original List: {sample_list}") print(f"Extracted Keywords: {result}") 

When you run the program, you'll get:

Original List: ['apple', 'for', 'banana', 'while', 'cherry', 'loop'] Extracted Keywords: ['for', 'while'] 

Explanation:

  1. We define a function extract_keywords_from_list that takes a list of strings (string_list) and a set of keywords (keywords) as arguments.
  2. Inside the function, we use list comprehension to iterate over the strings in string_list. For each word, we check if it is present in the keywords set using the in keyword.
  3. The function returns a new list containing only the words that are also present in the set of keywords.
  4. We then test the function with a sample list and a set of predefined keywords, then print the results.

Note that we use a set for predefined_keywords because checking membership in a set is generally faster than checking membership in a list, especially when the set is large.


More Tags

sobel reduction addeventlistener controlvalueaccessor bundling-and-minification xslt-3.0 phone-number managedthreadfactory laravel-migrations date-conversion

More Programming Guides

Other Guides

More Programming Examples