Python发现不起作用

Python发现不起作用,python,Python,在以下程序中查找似乎不适用于“.”、“!”和“?”字符。有人能帮我找出错误吗 我试过以下几件事: a。在搜索条件中添加反斜杠 b。在搜索条件中添加两个反斜杠 如果你看打印的结果。。你会发现find不能正确地用于句子。你能帮我找出哪里出了问题吗 提前谢谢 #!/usr/bin/python import sys import csv # In this exercise, we are interested in the field 'body' (which is the 5th field,

在以下程序中查找似乎不适用于“.”、“!”和“?”字符。有人能帮我找出错误吗

我试过以下几件事:

a。在搜索条件中添加反斜杠

b。在搜索条件中添加两个反斜杠

如果你看打印的结果。。你会发现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()
find(…)

-1
的计算结果为
True
。因此,如果未找到子字符串,它将计算为
True
。如果在字符串开头找到子字符串,它将返回
0
,并计算为
False
。如果在字符串的其他位置找到它,它将返回一个大于零的索引,并且计算结果为
True

在中使用

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

只有在需要查找索引时才使用
str.find

缩进被破坏
if '.' in line[4]:
    # ...