使用python松散地搜索句子中的多个单词
我试图搜索字符串中的单词,但我的输出为false,因为由于复数因素,“men”和“shirt”在字符串中不匹配。我真正想要的是将“男士”与“男士”匹配,并将“衬衫”与“衬衫”匹配。我如何做到这一点,如果有一种简单的方法可以在python中实现这一点,请与我们分享使用python松散地搜索句子中的多个单词,python,string,python-2.7,Python,String,Python 2.7,我试图搜索字符串中的单词,但我的输出为false,因为由于复数因素,“men”和“shirt”在字符串中不匹配。我真正想要的是将“男士”与“男士”匹配,并将“衬衫”与“衬衫”匹配。我如何做到这一点,如果有一种简单的方法可以在python中实现这一点,请与我们分享 strings = ['get-upto-70-off-on-mens-t-shirts'] words = ['men','shirt'] print map(lambda x: all(map(lambda y:y in x.spl
strings = ['get-upto-70-off-on-mens-t-shirts']
words = ['men','shirt']
print map(lambda x: all(map(lambda y:y in x.split(),words)),strings)
输出
False
您可以在
NTLK
库中使用lemmatization(删除's'ing'等),也可以使用fuzzyfuzzy
库进行模糊字符串匹配。一种可能性是使用Python的内置difflib
模块。函数get\u close\u matches()
()可能需要一些调整:
import difflib
strings = ['get-upto-70-off-on-mens-t-shirts']
words = ['men','shirt']
for w in words:
for s in strings:
s = s.split('-')
m = difflib.get_close_matches(w, s)
print('Word: "{}" Close matches: {}'.format(w, m))
印刷品:
Word: "men" Close matches: ['mens']
Word: "shirt" Close matches: ['shirts']
在我脑海中,你可以选择两件事中的一件:检查单词是否在候选短语中,或者计算单词和候选短语之间的距离,如果低于某个阈值,则将其视为匹配项。