2016-05-25 9 views
-4

次のプログラムで検索すると、 '。'、 '!'と '?'文字。誰かがエラーを理解するのを助けることができますか?Pythonが動作しないfind

は、私は、次のことを試してみた:

。検索条件にバックスラッシュを付ける

b。検索基準に2つのバックスラッシュを入れます。

Printの結果を見ると、findが文章に対して正しく機能しないことがわかります。何が間違っているのか理解してもらえますか?

ありがとうございます!

#!/usr/bin/python 
import sys 
import csv 

# In this exercise, we are interested in the field 'body' (which is the 5th field, 
# line[4]). The objective is to count the number of forum nodes where 'body' either 
# contains none of the three punctuation marks: period ('.'), exclamation point ('!'), 
# question mark ('?'), or else 'body' contains exactly one such punctuation mark as the 
# last character. There is no need to parse the HTML inside 'body'. Also, do not pay 
# special attention to newline characters. 

def mapper(): 
    ct = 0 
    reader = csv.reader(sys.stdin, delimiter='\t') 
    writer = csv.writer(sys.stdout, delimiter='\t', quotechar='"', quoting=csv.QUOTE_ALL) 

    for line in reader: 

    try: 
     if line[4].strip().find('\\.') : 
     writer.writerow(line) 
     print ".", " found" 
     ct = ct + 1 
    except: 
     print "Error from .", sys.exc_info()[0] 

    try: 
     if line[4].strip().find("!") : 
     writer.writerow(line) 
     print "!", " found" 
     ct += 1 
    except: 
     print "Error from !" 

    try: 
     if line[4].strip().find('\\?') : 
     writer.writerow(line) 
     print "?", " found" 
     ct += 1 
    except: 
     print "Error from ?"   
#   if count == 0 or count == 3 : 
#    totalLines += 1 
#    writer.writerow(line) 



test_text = """\"\"\t\"\"\t\"\"\t\"\"\t\"This is one sentence\"\t\"\" 
\"\"\t\"\"\t\"\"\t\"\"\t\"Also one sentence!\"\t\"\" 
\"\"\t\"\"\t\"\"\t\"\"\t\"Hey!\nTwo sentences!\"\t\"\" 
\"\"\t\"\"\t\"\"\t\"\"\t\"One. Two! Three?\"\t\"\" 
\"\"\t\"\"\t\"\"\t\"\"\t\"One Period. Two Sentences\"\t\"\" 
\"\"\t\"\"\t\"\"\t\"\"\t\"Three\nlines, one sentence\n\"\t\"\" 
""" 

# This function allows you to test the mapper with the provided test string 
def main(): 
    import StringIO 
    sys.stdin = StringIO.StringIO(test_text) 
    mapper() 
    sys.stdin = sys.__stdin__ 

if __name__ == "__main__": 
    main() 
+0

インデントが壊れている –

答えて

2

find(...)

S.find(sub [,start [,end]]) -> int 

Return the lowest index in S where substring sub is found, 
such that sub is contained within S[start:end]. Optional 
arguments start and end are interpreted as in slice notation. 

Return -1 on failure. 
-1

Trueとして評価します。したがって、部分文字列が見つからない場合は、Trueと評価されます。部分文字列が文字列の先頭にある場合は、0を返し、Falseと評価します。文字列の他の場所に見つかった場合は、0より大きいインデックスが返され、Trueと評価されます。

代わりinを使用する:あなたは、インデックスを見つける必要があるとき

if '.' in line[4]: 
    # ... 

のみstr.findを使用しています。

関連する問題