有没有更Pythonic的方式来编写这个脚本?我想在学习语言的过程中养成良好的习惯

问题描述 投票:0回答:2

此函数获取在命令行上写入的文件名,然后打印文件的代码行数,忽略注释和空行。

from sys import argv

try:
    with open(argv[1],"r") as file:
        content = [line.strip() for line in file.readlines() if line.strip()!=""] #stores all char lines as strings

        i=0
        for line in content:
            if line[0].isalnum():
                i += 1
            else:
                continue

        print(f"Total lines of code: {i}")

except FileNotFoundError:
    print("that file doesn't exist")

它按预期运行,尽管我不确定在这里使用较长的列表理解是否是一个好的做法,特别是对于我塞入其中的所有字符串方法。

我尝试将空字符串检查放入 bool 块中,但它似乎可读性较差,我想减少对 bool 循环的依赖。

python methods boolean
2个回答
0
投票

一些建议,不一定是“Pythonic”,但无论如何都是好的:

  1. 避免每行拨打
    strip()
    两次
  2. 您的循环中不需要显式的
    continue
  3. 如果可能,请严格处理异常,即只有文件打开位需要位于 try 块中

0
投票

改进:

  1. 如果不需要,请不要创建
    list
    (您创建了两个,一个包含不必要的
    .readlines()
    调用,另一个包含 listcomp 本身)
  2. 空字符串是假的,不需要将它们与空字符串进行比较
  3. 您可以使用海象运算符(
    :=
    ,又名赋值表达式)来避免
    strip
    两次
  4. 您可以使用
    sum
    功能来合计
  5. else: continue
     控制循环中的所有其他代码时,
    if
    毫无意义

缩写代码:

from sys import argv

try:
    with open(argv[1],"r") as file:
        i = sum(1 for line in file
                  if (stripped := line.strip()) and stripped.isalnum())
        print(f"Total lines of code: {i}")
except FileNotFoundError:
    print("that file doesn't exist")

这涉及到临时

list
(因此只要任何给定的不超过您的可用内存,它就可以处理任何大小的文件),并且作为奖励,运行速度应该会稍快一些。

© www.soinside.com 2019 - 2024. All rights reserved.