简体   繁体   中英

Find longest substring in python

I have an input string and a file composed of different strings, one per line. I am trying to find if there is a substring in the input string that matches an entire line in the file. Its working but because there are some lines in the file that happen to be substrings of other lines, I'm not always getting the correct result. So is there a way to find the longest substring that matches a line in the file? For example, say the file contained: car, red car. And my input was "I like my red car." Is there a way to return "red car" rather than just "car"?

Here's my code:

wordsDoc = open('Database.txt', 'r', encoding='latin-1')
words = wordsDoc.readlines()
for line in words:
    if line.strip().lower() in inputString.lower():
        matching.append(line)

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