简体   繁体   中英

How can I remove all comments from a Python script?

I get a file from the desktop that has a code of python like:

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

and I want to print in the programme :

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

and I run in it my programme with fopen and I get any line apart, I want to print the lines but without the #...the # must be checked if is in "" or '' and if it is when we must print the line with the #.

I have open a file and get the lines apart and checked if the # is in the line when removing it but I can't find who to check if the # is in "" or '' and if it is then print all the line.

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)

and the result is :

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

The function string.find() returns the index of first occurence of the substring . So in your case you want to look for lines where it returns 0 (then the # is the first character, ie a comment).

So you could do something like

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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