0

我陷入了困境。我正在尝试编写一个程序,在其中检查一段文本以查找用户插入的单词。程序应该说明单词在哪一行以及它在该行中出现了多少次。到目前为止,这是我的代码:

def linecount(t, w):

    f=0
    s=[]
    c=0
    for x in t:
        if not(x == '\n'):
            s=list(s)+list(x)

        c=c+1
        #where this checks if x is a return or not(thus limiting to each line)

关于如何进行的任何建议?

4

1 回答 1

0

对于您的情况,我认为您可以只使用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 指出的那样,您可以findCountline.count(word)...

于 2013-10-28T17:46:01.743 回答