简体   繁体   中英

Determine if a list of words is in order in a String in Python?

I want to write a python function to determine if a list of words exists in order in a string. If it does not, return the longest list of words that are in order in that string.

For example, let's suppose I have this sentence: The boy was walking his big dog down the street. And I have a list of words [boy, was, his, dog, street, the, down] . It is clear that in this case, boy, was and dog, street, the down both appear in succession in the sentence. Thus, my function should return these words in the order they appear, so: boy was and dog down the street .

Does anyone have an idea of how to do this in an efficient way?

Thanks

Edit from comment: You just need to return the sets of words that appear in the string in order and are also in the list. Of course, they should be as long as they can be. That's why in the example I returned dog down the street since all of those words are in my list and also appear next to each other in the string.

I figured out how to do it:

def order(sentence, wordList):
    s_list = sentence(' .', '').replace('. ', '').replace('.', '').split(' ')

    returnSentence = ""
    returnSentenceLen = 0
    previousPos = 0
    currentSentence = []
    # iterate through all the words in the matched list and find the ones that are together
    for i, word in enumerate(s_list):
        # this word is in our list of words
        if word in wordList:
            currentSentence.append(word)
            if i == 0:
                previousPos = 0
            else:
                if (i - previousPos) == 1:
                    # this should now be our new sentence of continuous words
                    if (len(currentSentence) > returnSentenceLen):
                        returnSentence = ' '.join(word for word in currentSentence)
                        returnSentenceLen = len(currentSentence)
                else:
                    currentSentence = []
                    currentSentence.append(word)
                previousPos = i
    return returnSentence

print(order('The boy was walking his dog down the street.', ['boy', 'was', 'dog', 'street', 'the', 'down']))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM