繁体   English   中英

Python:需要一个缩进块

[英]Python:Expected an indented block

我正在尝试使用 mapreduce 运行 2 个 python 程序,并且每次运行它们时都会出现错误。 下面是这两个文件的代码。 它一直告诉我在两个程序中的 main(sys.argv) 命令中都会出现预期的缩进块错误。 任何指导都会受到赞赏。

映射器

#!/usr/bin/env python
#Be sure the indentation is identical and also be sure the line above this is on the first line

import sys
import re

def main(argv):
    line = sys.stdin.readline()
    pattern = re.compile("[a-zA-Z0-9]+")
    while line:
        for word in pattern.findall(line):
            print(word+"\t"+"1")
    line = sys.stdin.readline()
#Note there are two underscores around name and main
    if __name__ == "__main__":
        main(sys.argv)

减速器.py

#!/usr/bin/env python
#Be sure the indentation is correct and also be sure the line above this is on the first line

import sys

def main(argv):
    current_word = None
    current_count = 0
    word = None
    for line in sys.stdin:
        line = line.strip()
        word, count = line.split('\t', 1)
        count = int(count)
        if current_word == word:
            current_count += count
        else:
            if current_word:
                print('%s\t%s' % (current_word, current_count))
            current_count = count
            current_word = word
    if current_word == word:
        print('%s\t%s' % (current_word, current_count))

#Note there are two underscores around name and main
    if __name__ == "__main__":
        main(sys.argv)

错误信息:

[maria_dev@sandbox-hdp ~]$ python reducer.py                                                                                                                                                                       
  File "reducer.py", line 25
    main(sys.argv)                                                                                                                                                                                                 
       ^                                                                                                                                                                                                           
IndentationError: expected an indented block

Mapper 文件示例映射器

if __name__ == "__main__":
    # some
    # commands
    # doing
    # stuff

这是 Python 中编写库时使用的一个不错的小“技巧”​​。 import库时,您通常只想导入类和函数,但不想执行示例代码。 当您将库文件作为独立脚本执行时,情况有所不同。 当你这样做时,你会期望一些关于如何使用该库的示例的输出。 在 Python 中,这是通过if __name__ == "__main__": __name__是一个包含特定于当前文件的字符串的变量。 对于主文件,此字符串始终为值"__main__"因此这是一种判断文件是执行的主文件还是只是某个库的简单方法。

主要问题是缩进。 Python 只能通过缩进告诉逻辑代码块(例如函数定义、if 子句或循环的主体)。 如果 Python 告诉您存在IndentationError ,则很可能是格式错误的代码造成的。 如果混合使用制表符和空格,也会引发此错误,因此请小心避免这种情况。 黄金标准是缩进 4 个空格,而不是制表符。

此外,使用if __name__ == "__main__":在缩进上下文中几乎没有意义。 完全删除该块(如果您只将这些文件用作库)或取消缩进它是相当节省的,以便if完全不缩进并且 if 子句的主体缩进 4 个空格。

您应该在main函数之外使用if __name__ == "__main__":块。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM