Python2.7:返回超过5个单词的行的总数

Python2.7:返回超过5个单词的行的总数,python,python-2.7,Python,Python 2.7,这段代码只是作为类中的一个示例在黑板上给出的,但是当我尝试用python执行它时(我们使用2.7),它不起作用。 代码应该读取文本文件管理中的所有行,每行只能由数字或字符组成。如果该行不包含数字且超过5个字,则长行数增加1。 但是,在单词数_中,返回值不大于1,因此def long(line)始终返回false,并且长_行的打印数字_的输出保持在0。在本例中,长\u行的打印编号\u的输出应为3。这个代码哪里出错了 LONG_LINE_BORDER = 5 file = open('adminis

这段代码只是作为类中的一个示例在黑板上给出的,但是当我尝试用python执行它时(我们使用2.7),它不起作用。 代码应该读取文本文件管理中的所有行,每行只能由数字或字符组成。如果该行不包含数字且超过5个字,则长行数增加1。 但是,在单词数_中,返回值不大于1,因此def long(line)始终返回false,并且长_行的打印数字_的输出保持在0。在本例中,长\u行的打印编号\u的输出应为3。这个代码哪里出错了

LONG_LINE_BORDER = 5
file = open('administration')
input = file.read()
lines = input.splitlines()

print(lines)

def word(string):
    for c in string:
        if not c.isalpha():
            return False
    return True

def number_of_words(line):
    strings = line.split()
    for string in strings:
        result = 0
        if word(string):
            result += 1
    return result

def long(line):
    return number_of_words(line) > LONG_LINE_BORDER

number_of_long_lines = 0

for line in lines:
    if long(line):
        number_of_long_lines += 1
print number_of_long_lines
管理输入文件:

a b c d
a b c d e f
a b c d e f g
5 6 7 3
1 2 3 4 5 6
a b c d e f g h

在每次调用
word()
函数之前,为结果重新定义一个0值。从for循环中获取
result=0

LONG_LINE_BORDER = 5
file = open('administration')
input = file.read()
lines = input.splitlines()

print(lines)

def word(string):
    for c in string:
        if not c.isalpha():
            return False
    return True

def number_of_words(line):
    strings = line.split()
    result = 0 #put this here
    for string in strings:  
        if word(string):
            result += 1
    return result

def long(line):
    return number_of_words(line) > LONG_LINE_BORDER

number_of_long_lines = 0

for line in lines:
    if long(line):
        number_of_long_lines += 1
print number_of_long_lines

您可以为行中的每个单词重置
result=0
。将其移出包含循环。使用调试器将帮助您找到错误。@0x5453解决了问题!谢谢,谢谢!这是有道理的