2012-09-11 38 views
1

我的導師Barry總是在踢我忘記在我的逗號之後加上空格,等號和在文件末尾留下太多行。我想練習一些python並編寫一個解析器來檢查我的文件,然後將它們呈現給他。解析一個python文件來檢查它是否符合某些規則

#BarryParser v0.1 

from re import findall, search 

def comma_checker(line, lineno): 
    """ Checks commas have a space after them """ 
    split_line = line.split(', ') 
    for string in split_line: 
     found_error = findall('.*,.*', string) 
     if found_error: 
      print "BARRY ISSUE DETECTED: COMMA ERROR LINE: %s: %s" % (lineno, line) 

def equals_checker(line, lineno): 
    split_line = line.split(' = ') 
    for string in split_line: 
    found_error = findall('.*==?.*', string) 
    if found_error: 
     print "BARRY ISSUE DETECTED: EQUALS ERROR LINE: %s: %s" % (lineno, line) 

def too_many_blank_lines(lines): 
    """if the last line is a new line and the line before is also a new line, 
     rasises barry issue over too many blank lines 
    """ 
    last_line = lines[len(lines)-1] 
    second_to_last_line = lines[len(lines)-2] 
    if last_line == "\n" and second_to_last_line == "\n": 
     print "BARRY ISSUE DETECTED: TOO MANY BLANK LINES AT END OF TEXT" 
    elif search('\t*\n{1}', last_line)and search('\t*\n{1}', second_to_last_line): 
     print "BARRY ISSUE DETECTED: TOO MANY BLANK LINES AT END OF TEXT" 
    elif search('\t*\n{1}', second_to_last_line) and last_line == "\n": 
     print "BARRY ISSUE DETECTED: TOO MANY BLANK LINES AT END OF TEXT" 

def main(): 
    file = open("test.txt") 
    line_no = 0 
    lines = file.readlines(100000) 
    too_many_blank_lines(lines) #CHECK FOR BLANK LINES AT END OF TEXT 
    for line in lines: 
     line_no +=1 
     if not line == "\n": 
      if not line[:1] == "#": 
       comma_checker(line, line_no) #CHECK COMMAS ARE DONE RIGHT 
       equals_checker(line, line_no) #CHECK EQUALS HAVE SPACES AFTER & BEFORE 

if __name__ == '__main__': 
    main() 

它將解析python文件。問題是,我無法弄清楚如何讓等位處理==和=方法相同。

+2

有幾個工具爲你做這種事情了偉大的工作:?pylint的,PyChecker或PyFlakes(HTTP:/ /stackoverflow.com/q/1428872)。例如,請查看http://pypi.python.org/pypi/pep8爲您完成這些測試。 –

+0

有什麼問題? – lolopop

+0

有問題嗎? :) –

回答

1

看看pep8模塊。這會檢查您的代碼是否符合pep8編碼標準。

參見:http://www.python.org/dev/peps/pep-0008/

下面是示例輸出

[email protected]:~> pep8 *.py 
1.py:11:1: W293 blank line contains whitespace 
1.py:14:80: E501 line too long (81 characters) 
1.py:24:1: E302 expected 2 blank lines, found 1 
1.py:37:23: W291 trailing whitespace 
1.py:90:27: E201 whitespace after '[' 
1.py:116:36: E701 multiple statements on one line (colon) 
1.py:144:9: E303 too many blank lines (2) 
2.py:22:1: W391 blank line at end of file 
3.py:75:29: E231 missing whitespace after ',' 
+0

這是完美的,可以從這裏竊取我需要的東西。謝謝! – Noelkd

+0

很高興聽到這一點。快樂的偷竊。 –

0

使用Pylint爲您檢查程序。

相關問題