【问题标题】:Count the line only when special characters are present仅当存在特殊字符时才计算行数
【发布时间】:2019-07-31 14:26:33
【问题描述】:

我只想在行中出现特殊字符时才计算行数。

count=0
with open (xvg_input, 'r') as cavity_count:
    line_to_end = cavity_count.readlines()
    for line in line_to_end:
        if "#" in line and "@" in line:
            count +=1
        print (count)    

只想在有特殊字符的时候计算行数。

【问题讨论】:

  • 这里有什么问题?你的输入是什么样的?
  • 现在您的代码只计算同时具有@# 的行
  • if re.match("^[a-zA-Z0-9_]*$", line): count+=1
  • @ xaxis label "Frame" @ yaxis label "Volume (Angstroms\S3\N)" @ s0 legend "Total" @ s1 legend "Cavity 1" @ s2 legend "Cavity 2"

标签: python python-3.x file-handling


【解决方案1】:

我假设,您想计算出现特殊字符的总行数。如果是这种情况,请移出打印件。它在内部缩进了两层。

您的代码有很小的变化(如果您只关心“#”或“@”,否则请告诉我们)。

count=0
with open (xvg_input, 'r') as cavity_count:
    line_to_end = cavity_count.readlines()
    for line in line_to_end:
        if "#" in line or "@" in line:
            count +=1
print(count) 

但是,如果您想计算其他属性,则此方法将不起作用。如果这不是您想要的,请告诉我们。

【讨论】:

  • 我也试过这个,但计数仍然为零。
  • 您希望“#”和“@”同时出现在同一行中,还是希望其中任何一个出现?
  • 他们中的任何一个都会出现
  • 从字面上看这是愚蠢的错误:( :(。感谢您的帮助
【解决方案2】:
from string import punctuation
with open(xvg_input, 'r') as cavity_count:
    print(len(
             ['' for line in cavity_count
                if any(char in line for char in punctuation)]
          ))

或者如果你想用那个计数来做些事情,只需将它保存到任何 var 而不是打印

【讨论】:

  • 它正在计算整行。
  • 为什么?它检查是否有任何标点字符在行中,因此它不会计算没有标点字符的行。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-08-11
  • 2021-10-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-06-29
相关资源
最近更新 更多