对于您的情况,我认为您可以只使用find
字符串的方法:
def findCount(line, word):
count = 0
idx = line.find(word)
while idx >= 0: # word has been found at least once
count += 1
# Searching the next occurence
idx = line.find(word, idx + len(word))
return count
然后,您可以像以前那样遍历这些行:
def findCounts(lines, word):
for i, line in enumerate(lines):
print "Lines %s: found %s times word %s..." % (i, findCount(line, word), word)
哪个输出:
>>> text = '''lapin souris lapin lapin\nlapin lapin\n\n\nchat chien\n lapin chat chien'''.split('\n')
>>> print text
['lapin souris lapin lapin', 'lapin lapin', '', '', 'chat chien', ' lapin chat chien']
>>> findCounts(text, 'lapin')
Lines 0: found 3 times word lapin...
Lines 1: found 2 times word lapin...
Lines 2: found 0 times word lapin...
Lines 3: found 0 times word lapin...
Lines 4: found 0 times word lapin...
Lines 5: found 1 times word lapin...
- 编辑 -
或者,正如 hcwhsa 指出的那样,您可以findCount
用line.count(word)
...