我正在尝试使用mapreduce运行2个python程序,并在每次运行它们时均出现错误。以下是这两个文件的代码。它一直告诉我,在两个程序的main(sys.argv)命令中都出现了缩进的块错误。任何指导都将得到认可。
Mapper.py
#!/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)
reducer.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
答案 0 :(得分:1)
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个空格。
答案 1 :(得分:0)
您应该在if __name__ == "__main__":
函数外部使用main
块。