2013-10-28 88 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