对于你的情况,我想你可以只使用字符串的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指出的那样,你可以代替我needlessely复杂findCount
通过line.count(word)
......
来源
2013-10-28 17:46:01
val
#Nice人们如何投票并查看该问题,但不能提供对如何进行任何指针,特别是考虑到并不是每个人都是一个程序员...... – Morgormir
对于子字符串检查,使用'in'运算符:''x'in'fox''。对于count,使用'str.count':''foo foo foo'.count('oo')'。 –
谢谢我没有想到这一点。 – Morgormir