2015-01-06 135 views
1

我有一個字符串變量,它包含來自大型文本文件的輸入。文本文件中的註釋以'#'開始並以新行結束。從字符串中剝離註釋行

所以,我想要做的是從這個字符串中生成另一個字符串,其中所有以'#'開頭並以換行符結尾的註釋行都被刪除。

所以,我想我可以做一些事情,我可以在字符串分割爲:

def transform_string(input): 
    output = '' 
    # Look for # 
    sub_strs = input.split('#') 
    for s in sub_strs: 
     # Look for newline 
     sub_sub_strs = s.split('\r\n') 
     for j in sub_sub_strs: 
      output += j 

return output 

不過,看起來醜陋,我想知道是否有一個更優雅,Python的方式來做到這一點。另外,這很容易出錯。因爲每個'#'將有一個對應的換行符,我想在第一次出現時進行拆分,而不是根據'\ r \ n'進行拆分。

+1

評論總是整行嗎?如果是這樣,將文件處理爲行列表而不是一個長字符串會更容易。 – jonrsharpe

回答

2

發電機可能是最Python化的解決方案在這裏:

def clean_input(filename): 
    with open(filename, 'r') as f: 
     for line in f: 
      if not line.lstrip().startswith('#'): 
       yield line 

for line in clean_input('somefile.txt'): 
    ... 

這可以讓你移動註釋剝離,或其他任何預處理您需要遠離文件的實際處理,您只需遍歷已清理的數據即可。

+0

很多很好的答案,但我只能選擇一個!我結束了這個解決方案。 – Luca

2

正則表達式可以工作:

# Python 2.7 
import re 

def stripComment(text): return re.sub(r'#.*$', '', text) 

print(stripComment("Hello there")) 
# Hello there 

print(stripComment("Hello #there")) 
# Hello 

這應該允許的是整行註釋處理,或行,其中的意見在中間某個地方開始(保留之前的評論內容)

1

至於你提到你是從一個文本文件閱讀,你最好在你閱讀的文件,這樣做:

data = [] 
with open("input_file.txt") as f: 
    for line in f: 
     if not line.startswith("#"): 
      data.append(line) 

data = "".join(data) 

這最後一步拼接是不是最佳 - 如果可以的話,你應該分別處理每一行,因此你不需要整個文件在內存中。

+0

或者列表comp - 'data = [line中的行如果不是line.startswith(「#」)]' – jonrsharpe

0

你可以使用列表解析來過濾行:

>>> txt = """some lines 
... #some commented 
... some not 
... #othe comment 
... other line""" 
>>> '\n'.join(line for line in txt.splitlines() if not line.startswith('#')) 
'some lines\nsome not\nother line'