2017-01-31 4 views
3

ファイルを入力として受け付け、フルラインのコメントである行数を出力する関数を作成しようとしています(つまり、コメントは#で始まります)。Pythonでフルラインコメントの行数をどのように数えますか?

は、たとえば次の行は、結果2を印刷する必要があります言う含むファイル:

abc 
#some random comment 
cde 
fgh 
#another random comment 

これまでのところ、私はの線に沿ってみましたが、ちょうどハッシュ記号拾っていない:

infile = open("code.py", "r") 
line = infile.readline() 

def countHashedLines(filename) : 

    while line != "" : 
      hashes = '#' 
      value = line 
      print(value) #here you will get all 
      #if(value == hashes): tried this but just wasn't working 
      #  print("hi") 
      for line in value: 
      line = line.split('#', 1)[1] 
      line = line.rstrip() 
      print(value) 
      line = infile.readline() 
    return() 

ありがとうございます。 Jemma

答えて

1

使いやすさ(主観的)のためにいくつかのステートメントを書き直しましたが、これはあなたに望ましい出力を与えます。ここで

def countHashedLines(lines): 
    return len([line for line in lines if line.startswith('#')]) 
0

標準入力でファイルを渡します。

import sys 

count = 0 

for line in sys.stdin: """ Note: you could also open the file and iterate through it""" 
    if line[0] == '#': """ Every time a line begins with # """ 
     count += 1 """ Increment """ 


print(count) 
0

は、正規表現を使用し、フロントにホワイトスペースを持っているコメントを検出し、別の解決策である

def countHashedLines(lines): 
    tally = 0 
    for line in lines: 
     if line.startswith('#'): tally += 1 
    return tally 

infile = open('code.py', 'r') 
all_lines = infile.readlines() 

num_hash_nums = countHashedLines(all_lines) # <- 2 

infile.close() 

...またはあなたが機能のコンパクトかつクリーンなバージョンをしたい場合は... 。

import re 

def countFullLineComments(infile) : 
    count = 0 
    p = re.compile(r"^\s*#.*$") 
    for line in infile.readlines(): 
     m = p.match(line) 
     if m: 
      count += 1 
      print(m.group(0)) 
    return count 

infile = open("code.py", "r") 
print(countFullLineComments(infile)) 
関連する問題