2013-10-28 85 views
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) 

如何进行的任何建议吗?

+0

#Nice人们如何投票并查看该问题,但不能提供对如何进行任何指针,特别是考虑到并不是每个人都是一个程序员...... – Morgormir

+0

对于子字符串检查,使用'in'运算符:''x'in'fox''。对于count,使用'str.count':''foo foo foo'.count('oo')'。 –

+0

谢谢我没有想到这一点。 – Morgormir

回答

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指出的那样,你可以代替我needlessely复杂findCount通过line.count(word) ......

+0

我已经尝试过line.count,但似乎无法让它返回确切的单词......它会返回具有给定单词的所有单词。 EX:findcount('他们的猫在桌子上,''')返回2而不是1 ... 但是,多亏了所有人,现在更清楚 – Morgormir

+0

是的,它只计算_substrings_,而不是_words_。要做到这一点,你可以修改'findCount',这样在成功找到之后,它会向前看一个字符以确保它是一个'单词'(即后跟空格,逗号,句点......)或者看*正则表达式*(正则表达式模块在这里:http://docs.python.org/2.7/library/re.html)基本上提供了一个更好的框架来做同样的事情。 – val