Python -- 搜索子串全词)

Python -- Search Subsrtring Full Word(s)

我想查找子字符串在字符串中出现的次数。我在做这个

termCount = content.count(term)

但是如果我像 "Ford" 这样搜索,它返回的结果集就像

"Ford Motors"         Result: 1 Correct
"cannot afford Ford"  Result: 2 Incorrect
"ford is good"        Result: 1 Correct

搜索字词可以有多个字词,例如 "Ford Motors" 或 "Ford Auto"。 例如,如果我搜索 "Ford Motor"

"Ford Motors"               Result: 1 Correct
"cannot afford Ford Motor"  Result: 1 Correct
"Ford Motorway"             Result: 1 InCorrect    

我想要的是不区分大小写并且作为一个整体搜索它们。意思是,如果我搜索一个子字符串,它应该作为一个整体作为一个词或一个短语(在多个术语的情况下)包含,而不是该词的一部分。而且我还需要计算条款。我如何实现它。

你可以使用regex,在这种情况下使用re.findall然后得到匹配列表的长度:

re.findall(r'\byour_term\b',s) 

Demo

>>> s="Ford Motors cannot afford Ford Motor Ford Motorway Ford Motor."
>>> import re
>>> def counter(str,term):
...    return len(re.findall(r'\b{}\b'.format(term),str))
... 
>>> counter(s,'Ford Motor')
2
>>> counter(s,'Ford')
4
>>> counter(s,'Fords')
0

我会用空格分割字符串,这样我们就有了独立的词,然后我会从那里进行计数。

terms = ['Ford Motors', 'cannot afford Ford', 'ford is good'];
splitWords = [];

for term in terms:
    #take each string in the list and split it into words
    #then add these words to a list called splitWords.

    splitWords.extend(term.lower().split())

print(splitWords.count("ford"))