将 Python 2 程序移植到 Python 3,随机线生成器 [英] porting Python 2 program to Python 3, random line generator

查看:65
本文介绍了将 Python 2 程序移植到 Python 3,随机线生成器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用 Python2 编写的随机线生成器程序,但我需要将它移植到 Python3.你给程序一个选项 -n [number] 和一个文件参数,告诉它从文件中随机输出 [number] 行.这是程序的源代码:

I have a random line generator program written in Python2, but I need to port it to Python3. You give the program the option -n [number] and a file argument to tell it to randomly output [number] number of lines from the file. Here is the source for the program:

#!/usr/bin/python

import random, sys
from optparse import OptionParser

class randline:
    def __init__(self, filename):
        f = open(filename, 'r')
        self.lines = f.readlines()
        f.close()

    def chooseline(self):
        return random.choice(self.lines)

def main():
    version_msg = "%prog 2.0"
    usage_msg = """%prog [OPTION]... [FILE] [FILE]...

Output randomly selected lines from each FILE."""

    parser = OptionParser(version=version_msg,
                          usage=usage_msg)
    parser.add_option("-n", "--numlines",
                      action="store", dest="numlines", default=1,
                      help="output NUMLINES lines (default 1)")
    options, args = parser.parse_args(sys.argv[1:])

    try:
        numlines = int(options.numlines)
    except:
        parser.error("invalid NUMLINES: {0}".
                     format(options.numlines))
    if numlines < 0:
        parser.error("negative count: {0}".
                     format(numlines))
    if len(args) < 1:
        parser.error("input at least one operand!")

    for index in range(len(args)):
        input_file = args[index]
        try:
            generator = randline(input_file)
            for index in range(numlines):
                sys.stdout.write(generator.chooseline())
        except IOError as (errno, strerror):
            parser.error("I/O error({0}): {1}".
                        format(errno, strerror))

if __name__ == "__main__":
    main()


当我用 python3 运行它时:


When I run this with python3:

python3 randline.py -n 1 file.txt

我收到以下错误:

  File "randline.py", line 66
    except IOError as (errno, strerror):
                      ^
SyntaxError: invalid syntax

你能告诉我这个错误是什么意思以及如何解决吗?

Can you tell me what this error means and how to fix it?

谢谢!

推荐答案

这行语法不正确:

except IOError as (errno, strerror):

正确的形式是:

except IOError as err:

然后你可以检查err的属性,比如errno

then you can examine err for attributes like errno, etc.

我不确定你从哪里得到原始行,它也不是有效的 Python 2.x 语法.

I'm not sure where you got the original line from, it isn't valid Python 2.x syntax either.

这篇关于将 Python 2 程序移植到 Python 3,随机线生成器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆