對於你的情況,我想你可以只使用字符串的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