文本评估程序

时间:2013-10-28 17:23:51

标签: python python-2.7

我在一个车辙。 我正在尝试编写一个程序,其中检查用户插入的单词的文本段落。程序应说明该单词所在的行以及该行中存在的行数。 到目前为止,这是我的代码:

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)

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

1 个答案:

答案 0 :(得分: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所指出的那样,你可以用findCount替换我的一群复杂的line.count(word) ......