What is the best way to search for a specific word within a list of sentences, but only focusing on the first word of each sentence?

list = ["This is an example", "Hello there! This is an example"]


search = input("Enter keyword: ")

for title in list:
    if search in title:
        print(title)
#Output
Search: This
This is an example
Hello there! This is an example

This script searches for the input string, but I want it to specifically search for keywords that are at the beginning of a sentence. For example, if I enter "This" as the keyword, I only want it to find and display "This is an example" because "This" is the first word of a sentence.

Answer №1

Divide the phrase and check against the initial word in this manner:

p = ["Let's take a walk", "Hey, how's it going? Let's take a stroll together"]
lookup = input("Look up: ")
for item in p:
    if lookup == item.split()[0]:
        print(item)

Answer №2

A more concise solution using list comprehension:

l = ["This is an example", "Hello there! This is an example"]
s = input("Please enter a search string : ").lower()   #using lower function for case insensitive comparison
print("".join([i for i in l if i.split()[0].lower() == s]))

If you're not familiar with list comprehension, I recommend checking out the explanation by @not_speshal, as it provides a more detailed breakdown of the code.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Python code for clicking a button using Selenium

I'm having trouble closing popup windows in Selenium with Python. The button labeled "joyride-close-tip" is functioning correctly and closes the window, but the other two buttons are not working. What could be causing this issue? Even though I copied ...

Using Python to Validate Event Entries Against Variables

I am trying to implement Python code that can verify if a given `username` and `password` match an event trigger. The expected behavior is to print `correct` when there is a match, and `false` when they do not match. However, my current implementation alwa ...

Using regular expressions in python to parse an index of notification messages

Looking for a regular expression to extract message notifications from a GSM modem connected to the laptop via a serial port. The format typically appears like this: +CMTI: "SM",0 In this format, 0 represents the index number of the message stored on th ...

What is the best way to calculate the average within a specific time frame using Python

I am new to Python and seeking assistance. I need help creating a document with three columns: the first column should display dates like "2011.01", the second column should show the number of ARD 'events' in that month, and the third column shou ...

Issues with Selenium Geckodriver and ChromeDriver functionality

My attempts to run OS 10.12.6 with Selenium and Python 3.6 bindings have been unsuccessful thus far. The error message that keeps appearing is related to Geckodriver: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3 ...

How to add additional text after a particular line within a string containing multiple lines using JavaScript

What is the best way to add a new string after line 2 in a multi-line JavaScript string? ...

Is Python 2.7 still on my Mac? How can I check if Python 3.3 installation removes the older version?

Is it possible that there are concealed files lingering around? And is a re-installation of Python 2.7 necessary in order to use it? Appreciate your help! ...

Scraping URLs from src attribute with Python and Selenium: A step-by-step guide

My current project involves downloading multiple images and organizing them into folders using Selenium. The challenge I'm facing is extracting two ID's associated with each image from the URL. No matter what method I use - whether it's by t ...

Tips for handling occasional BadStatusLine and CannotSendRequest errors in Python WebDriver

After implementing selenium UI tests in Jenkins, a recurring issue has been observed with errors occurring during the tests. The errors encountered are BadStatusLine and CannotSendRequest errors that seem to occur randomly during selenium actions such as c ...

Exploring the einsum Function in Python

Utilizing einsum has proven to be incredibly efficient for me, consistently saving 2-3 lines of code each time I implement it. However, grasping its functionality has been quite challenging. For instance, when training a neural network and needing to comp ...

What's the best way to serialize a NumPy array without losing its matrix dimensions integrity?

numpy.array.tostring does not retain information about the dimensions of the matrix (refer to this question), leading users to use numpy.array.reshape. Is there a method to serialize a numpy array into JSON format while keeping this information? Note: Th ...

Create horizontal lines on a plot using Plotly

I've been attempting to overlay horizontal lines onto a candlestick chart using plotly, but I've run into an issue. The horizontal lines are not starting at their designated 'x' coordinate from df['date'][level[0]]; instead, t ...

Designate Identifier Upon Satisfaction of Conditions

I am working with two dataframes, df1 and df2. df1 contains latitude and longitude data for each observation, while df2 consists of latitude and longitude buckets that cover all possible combinations. Each bucket in df2 is assigned a unique "bucket ID". My ...

Combining multiple repositories using docker-compose

Currently, I have two services deployed on separate GitLab repositories but running on the same host using supervisord. The CI/CD process in each repository pushes code to this shared host. I am now looking to transition from supervisord to Docker. To beg ...

Creating a New Line in JSON Format Using Flask Python and Displaying it as HTML

I've been struggling to properly format JSON with new lines, but all my attempts have failed. from flask import * import json app = Flask(__name__) @app.route("/user/", methods=["GET"]) def user(): datajson = {"Author&q ...

How to extract the first row of values from grouped columns in a pandas dataframe

I am working with a dataframe where I need to add a new column called 'desired_output'. This new column should contain the first value of 'lumpsum' for each 'ID'. data = [ [1, 12334, 1, 12334], [1, 12334, 1, 12334], ...

Discover groups of microbial organisms

Looking to identify clusters of connected bacteria in a Python program using 4-connectivity. The input file format is structured as follows: ### ##### ####### ####### ...

Scraping Python Code for Various Size and Color Combinations

Looking to gather information on different sizes and colors of variants. Here's the situation at hand: Selected Color: -Mantis Green -Spool Yellow Selected Size: -6lb -8lb -10lb -15lb -20lb -30lb The goal is to extract the title, price, ...

What is the purpose of using the to_url() method within a path converter in Django?

What is the purpose of the to_url(self, value) method in a path converter within Django? I have come across only a few examples in the official documentation and I am struggling to grasp the significance of this method. Can someone explain exactly what t ...

Need to transform a column within a Pyspark dataframe that consists of arrays of dictionaries so that each key from the dictionaries becomes its own

I currently have a dataset structured like this: +-------+-------+-------+-------+ | Index |values_in_dicts | +-------+-------+-------+-------+ | 1 |[{"a":4, "b":5}, | | |{"a":7, "b":9}] | +----- ...