我需要在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('.')发布于 2014-06-03 04:48:39
我相信有一种更好的方法可以做到这一点,但这里是我的尝试
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发布于 2014-06-03 04:56:50
使用下面的代码去掉标点符号,然后比较它们:
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发布于 2014-06-03 13:44:21
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如果你真的很担心性能,并且有很多比较,你可以在字典中缓存翻译后的版本。
https://stackoverflow.com/questions/24002815
复制相似问题