首页 > 解决方案 > 如何计算仅包含一个逗号分隔的行数并忽略计算文本文件中两个逗号分隔的行数

问题描述

我想计算仅包含一个逗号分隔的行数并忽略计算文本文件中两个逗号分隔的行数

下面是我的代码

def countLines(filename):
   with open(filename,'r') as f: 
      CoList = f.split("\n") 
      Counter = 0 
      for i in CoList: 
          if i: 
             Counter += 1 
      return CoList

countLines('demo.txt')

标签: python

解决方案


我想这就是你想要的?

def countLines(filename):
    with open(filename,'r') as f: 
        Counter = 0 
        for line in f: 
            if line.count(',') == 1:
                Counter += 1 
      return Counter

推荐阅读