How to remove '#' comments from a string?

旧街凉风 提交于 2020-01-01 19:00:57

问题


The problem: Implement a Python function called stripComments(code) where code is a parameter that takes a string containing the Python code. The function stripComments() returns the code with all comments removed.

I have:

def stripComments(code):
   code = str(code)
   for line in code:
       comments = [word[1:] for word in code.split() if word[0] == '#']
       del(comments)
stripComments(code)

I'm not sure how to specifically tell python to search through each line of the string and when it finds a hashtag, to delete the rest of the line. Please help. :(


回答1:


You could achieve this through re.sub function.

import re
def stripComments(code):
    code = str(code)
    return re.sub(r'(?m)^ *#.*\n?', '', code)

print(stripComments("""#foo bar
bar foo
# buz"""))

(?m) enables the multiline mode. ^ asserts that we are at the start. <space>*# matches the character # at the start with or without preceding spaces. .* matches all the following characters except line breaks. Replacing those matched characters with empty string will give you the string with comment lines deleted.




回答2:


def remove_comments(filename1, filename2): """ Remove all comments beginning with # from filename1 and writes the result to filename2 """

with open(filename1, 'r') as f:
    lines = f.readlines()

with open(filename2, 'w') as f:
    for line in lines:
        # Keep the Shebang line
        if line[0:2] == "#!":
            f.writelines(line)
        # Also keep existing empty lines
        elif not line.strip():
            f.writelines(line)
        # But remove comments from other lines
        else:
            line = line.split('#')
            stripped_string = line[0].rstrip()
            # Write the line only if the comment was after the code.
            # Discard lines that only contain comments.
            if stripped_string:
                f.writelines(stripped_string)
                f.writelines('\n')


来源:https://stackoverflow.com/questions/28401547/how-to-remove-comments-from-a-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!