我需要在Python中使用或创建一个比较函数,也许已经存在这样做的方法?
我需要将字符串与列表中的值进行比较,并且我需要进行匹配,即使它有几个字符。我举个例子,这样你就能明白我的意思了。
示例1:
列表中的值:Name: This is the title
搜索值:Name This is the title
示例2:
列表值:Name and shortening m.m.
搜索值:Name and shortening m.m
正如您所看到的,我想要比较和需要匹配的值非常相似。搜索中的值是文件夹名称,所以它们有点不同,因为它们包含非法字符。
也许最简单的方法是在比较/:*?"<>|
和任何尾随点之前从字符串中删除不允许的字符。
关于比较字符串并获得匹配的最有效方法的任何提示是什么?
编辑:这样做是不是很难看?def Cleanup(Str):
Illegal = ['\','/',':','*','?','"','<','>','|']
return ''.join([char for char in Str if char not in Illegal]).rstrip('.')
我相信有更好的方法来做到这一点,但这里是我的尝试
import string
a = "Name: This is the title"
b = "Name This is the title"
# remove punctuation and make all lower-case
def strippedAndLowered(myString):
return "".join(i for i in myString if i not in string.punctuation).lower()
strippedAndLowered(a) == strippedAndLowered(b) # returns True
使用以下代码剥离标点符号,然后对它们进行比较:
def search(lst, item):
for i in lst:
i = ''.join([char for char in i if char.isalpha() or char == ' '])
if item == i:
return True
return False
translate
函数应该更快:
item = "Name: This is the title"
search = "Name This is the title"
illegal = r'/:*?"<>|'
def compare(s1, s2):
return s1.translate(None, illegal) == s2.translate(None, illegal)
print compare(search, item)
给了:
True
如果你真的很担心性能,并且有很多比较,你可以在字典中缓存翻译版本。