Python有string.find()和string.rfind()来获取字符串中子字符串的索引。
我想知道是否有像string.find_all()这样的东西可以返回所有找到的索引(不仅是从开始的第一个索引,还是从结束的第一个索引)。
例如:
string = "test test test test"
print string.find('test') # 0
print string.rfind('test') # 15
#this is the goal
print string.find_all('test') # [0,5,10,15]
要统计出现次数,请参见计算字符串中子字符串出现的次数。
当在一份文件中寻找大量的关键词时,使用flash文本
from flashtext import KeywordProcessor
words = ['test', 'exam', 'quiz']
txt = 'this is a test'
kwp = KeywordProcessor()
kwp.add_keywords_from_list(words)
result = kwp.extract_keywords(txt, span_info=True)
在大量搜索词列表上,Flashtext比正则表达式运行得更快。
同样,旧线程,但这里是我的解决方案使用生成器和普通str.find。
def findall(p, s):
'''Yields all the positions of
the pattern p in the string s.'''
i = s.find(p)
while i != -1:
yield i
i = s.find(p, i+1)
例子
x = 'banananassantana'
[(i, x[i:i+2]) for i in findall('na', x)]
返回
[(2, 'na'), (4, 'na'), (6, 'na'), (14, 'na')]