Method needed for skipping lines
Paul Hankin
paul.hankin at gmail.com
Wed Oct 31 20:04:51 EDT 2007
On Oct 31, 5:02 pm, Gustaf <gust... at algonet.se> wrote:
> Hi all,
>
> Just for fun, I'm working on a script to count the number of lines in source files. Some lines are auto-generated (by the IDE) and shouldn't be counted. The auto-generated part of files start with "Begin VB.Form" and end with "End" (first thing on the line). The "End" keyword may appear inside the auto-generated part, but not at the beginning of the line.
>
> I imagine having a flag variable to tell whether you're inside the auto-generated part, but I wasn't able to figure out exactly how. Here's the function, without the ability to skip auto-generated code:
>
> # Count the lines of source code in the file
> def count_lines(f):
> file = open(f, 'r')
> rows = 0
> for line in file:
> rows = rows + 1
> return rows
>
> How would you modify this to exclude lines between "Begin VB.Form" and "End" as described above?
First, your function can be written much more compactly:
def count_lines(f):
return len(open(f, 'r'))
Anyway, to answer your question, write a function that omits the lines
you want excluded:
def omit_generated_lines(lines):
in_generated = False
for line in lines:
line = line.strip()
in_generated = in_generated or line.starts_with('Begin
VB.Form')
if not in_generated:
yield line
in_generated = in_generated and not line.starts_with('End')
And count the remaining ones...
def count_lines(filename):
return len(omit_generated_lines(open(filename, 'r')))
--
Paul Hankin
More information about the Python-list
mailing list