简体   繁体   English

在python中找到最长的子字符串

[英]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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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