【问题标题】:How can I remove all comments from a Python script?如何从 Python 脚本中删除所有注释?
【发布时间】:2019-07-04 02:01:37
【问题描述】:

我从桌面得到一个文件,它的代码如下:

line 1 :#hi
line 2 :x=0
line 3 :#print x
line 4 :print "#" 
line 5 :print ' # the x is" , x 
line 6 :print "#"# 

我想在程序中打印:

line 1 :x=0
line 2 :print "#"
line 3 :print ' # the x is" , x
line 4 :print "#"

我用 fopen 在其中运行我的程序,我得到任何行分开,我想打印这些行但没有 #...必须检查 # 是否在 "" 或 '' 中,如果它是什么时候我们必须打印带有 # 的行。

我打开了一个文件,将行分开,并在删除它时检查#是否在行中,但我找不到谁来检查#是否在“”或“”中,如果是则打印所有的线。

def remove_comments(line,sep="#"):
    for s in sep:
        i = line.find(s)#find the posision of  #
        if i >= 0 :
            line = line[:i]#the line is until the # - 1
    return line.strip()

f=open("C:\Users\evogi\OneDrive\Desktop\ergasia3 pats\kodikaspy.txt","r")
for line in f :
    print remove_comments(line)

结果是:

line 1 :
line 2 :x=0
line 3 :
line 4 :print "
line 5 :print '
line 6 :print "

【问题讨论】:

标签: python


【解决方案1】:

函数string.find()返回子字符串第一次出现的索引。因此,在您的情况下,您要查找返回 0 的行(然后 # 是第一个字符,即注释)。

所以你可以做类似的事情

def remove_comments(line,sep="#"):
    for s in sep:
        i = line.find(s)#find the posision of  #
        if i == 0 :
            line = None
    return line.strip()

f=open("C:\Users\evogi\OneDrive\Desktop\ergasia3 pats\kodikaspy.txt","r")
for line in f :
    if remove_comments(line):
        print remove_comments(line)

【讨论】:

    猜你喜欢
    • 2020-07-14
    • 2012-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多