具有功能的执行

拉赫

似乎如果语句未执行,或者可能是因为我犯了一些错误。

我试过了,

ends = line.endswith('/')

if (line.startswith('  ') and ends == True)

但是不起作用。如果语句未运行

count = 0
for line in f1:
    if (line.startswith('  ') and line.endswith('/')):
        count = count + 1
        continue

    elif line.startswith(('  ', ' ', '//')):
        continue
    else:
        if (count == 0):
            f2.write(line)
            count = 0

如果行以“ //”开头或单行或双行空格,则不应打印这些行(条件1)。另外,如果一行以双倍空格开头,并以'/'结尾,并且下一行不满足条件1,则不应打印该行。无条件的行必须打印

输入:

//abcd

  abcd/

This line should not be printed

This has to be printed

预期产量:

This has to be printed

实际输出:

This line should not be printed

This has to be printed
吹牛

通过遍历文件对象生成的行始终以换行符结尾(除非它是文件的最后一行,并且文件不以尾随换行符结尾)。您可以rstripendswith测试行是否以某个特定字符结尾之前向该行申请另外,您还应该在代码重置counter(使用count = 0if (count == 0):否则该语句将永远不会运行:

from io import StringIO
f1 = StringIO('''//abcd
  abcd/
This line should not be printed
This has to be printed
''')
f2 = StringIO()
count = 0
for line in f1:
    if (line.startswith('  ') and line.rstrip().endswith('/')):
        count = count + 1
    elif not line.startswith(('  ', ' ', '//')):
        if (count == 0):
            f2.write(line)
        count = 0
print(f2.getvalue())

输出:

This has to be printed

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章