2015-02-09 45 views
2

問題: 實現一個名爲stripComments(code)的Python函數,其中code是一個接受包含Python代碼的字符串的參數。 stripComments()函數返回刪除了所有註釋的代碼。如何從字符串中刪除'#'註釋?

我:

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) 

我不知道如何明確告訴蟒蛇通過串的每一行進行搜索,當它找到一個主題標籤,刪除該行的其餘部分。 請幫忙。 :(

+0

一個例子會更好。 – 2015-02-09 01:37:12

+0

我沒有得到一個例子......我不知道它應該如何看待。 – 2015-02-09 01:46:26

回答

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>*#在開始帶或不帶空格前面的字符#相匹配。 .*匹配除換行符以外的所有字符,用空字符串替換這些匹配的字符將爲您提供刪除了註釋行的字符串

+0

好的,謝謝〜!這幫了很多。 – 2015-02-09 02:45:41

+1

很高興解決:-) – 2015-02-09 02:52:05

0

def remove_comments(filename1,fi lename2): 「」的「刪除文件名1#開頭的所有意見,並寫入 結果以文件名2 ‘’」

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')