【问题标题】:How to remove '#' comments from a string?如何从字符串中删除“#”注释?
【发布时间】:2015-02-09 01:35:45
【问题描述】:

问题: 实现一个名为 stripComments(code) 的 Python 函数,其中 code 是一个参数,它接受一个包含 Python 代码的字符串。函数 stripComments() 返回删除所有 cmets 的代码。

我有:

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)

我不确定如何具体告诉 python 搜索字符串的每一行,并在找到主题标签时删除该行的其余部分。 请帮忙。 :(

【问题讨论】:

  • 举个例子会更好。
  • 我没有给出一个例子......而且我不确定它应该是什么样子。
  • 考虑distutils.text_file.TextFile(file=io.StringIO(code)).readlines(),它根据需要使用TextFileStringIO

标签: string python-3.x comments


【解决方案1】:

你可以通过re.sub函数来实现。

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

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

(?m) 启用多行模式。 ^ 断言我们处于起步阶段。 <space>*# 匹配开头的字符 #,带或不带前面的空格。 .* 匹配除换行符以外的所有以下字符。用空字符串替换那些匹配的字符会给你删除注释行的字符串。

【讨论】:

  • 请注意,这不会删除活动代码行末尾的 cmets。
  • 请注意,如果代码行包含“#”作为代码的一部分,即使您通过从正则表达式中删除 ^ 将其修复为在活动代码行之后工作,这也将不起作用字符串
【解决方案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')

【讨论】:

  • 如果 # 作为代码的一部分包含在字符串中,结果会很糟糕
猜你喜欢
  • 2017-01-19
  • 2012-01-27
  • 2014-04-22
  • 1970-01-01
  • 1970-01-01
  • 2018-01-01
  • 2013-08-05
  • 2016-08-31
  • 1970-01-01
相关资源
最近更新 更多