【问题标题】:How to get the amount of 'strings'(?) and print [duplicate]如何获取“字符串”(?)的数量并打印[重复]
【发布时间】:2017-05-15 23:43:22
【问题描述】:

我在 .txt 中有一个用“:”分隔的不同单词的列表,例如:

banana:pinapple
apple:grapes
orange:nuts
...

如何获取分号左侧有单词的行数并打印该数字?

我用这个来分隔它们:

string1, string2 = line.split(':')

我想打印这样的数字:

print(number of lines where there exists is a string1)

【问题讨论】:

  • 天真的方式 - 拆分后将它们组合为一个列表并使用 Counter
  • @aryamccarthy 我想打印金额,所以我尝试了 print(len(string1)) 但我真的不知道要搜索什么。
  • 其他有点简单的方法是使用带有默认键的字典
  • @ADITYA 不清楚其意图是计算每个字符串还是简单地获取冒号左侧不为空的行数。
  • @aryamccarthy 简单算数写在括号里

标签: python


【解决方案1】:
count = 0
for line in f:
    string1, string2 = line.split(':')
    if string1:
        count += 1
print(count)

您的问题询问的是左边的字数,这正是这个数。这将处理行为:foo 的情况。不过,您并没有建议有没有冒号的行或有多个冒号的行。此外,您还没有说左边会有一个以上的单词。我选择忽略这些情况,因为您没有表明它们的存在。

【讨论】:

  • 基本上只计算文本文件中的行数也可以吗?
  • 处理:foo的情况。
  • @aryamccarthy 这是一个有效的案例吗? OP 的示例没有显示任何迹象表明存在 :foofoo::
  • 问题集中在左边,所以我谨慎概括。
  • @rbaleksandar 是的,这是真的......但要为每一种可能性做好准备,否则将面临追溯......
【解决方案2】:
fileName = 'myfile.txt'

counterDict = {}

with open(fileName,'r') as fh:
  for line in fh:
    left,right = line.rstrip('\n').split(':')
    counterDict[left] = counterDict.get(left,0)+1  

print(counterDict)

# cat myfile.txt

banana:pinapple
apple:grapes
orange:nuts
banana:pinapple
apple:grapes
orange:nuts
banana:pinapple
apple:grapes
orange:nuts

#结果

{'banana':3,'apple':3,'orange':3}

【讨论】:

    【解决方案3】:

    因此,根据提供的所有答案,我不确定我是否理解您的问题。您只想知道如何计算文本文件中的行数?

    是的,我看到您说“冒号左侧有一个单词”,但是为什么在没有任何其他文本的行中有一个冒号?您说您的程序以“示例”:“示例”的方式编写文本,对吗?

    如果是这种情况,您将不会在没有任何其他文本的行中使用冒号,除非您故意输入任何内容。

    def get_total_lines(self, path):
        counter = 0
        try:
            if os.path.isfile(path):
                with open(path, 'r') as inFile:
                    for i in enumerate(inFile):
                        counter = counter + 1
                        return str(counter)
            elif not os.path.isfile(path):
                print("Error: The file you're attempting to read does not exist, aborting reading process...")
        except IOError as exception:
            raise IOError('%s: %s' % (path, exception.strerror))
            return None
    

    这有一些基本形式的错误检查,这里没有它。

    def get_total_lines(self, path):
        counter = 0
        with open(path, 'r') as inFile:
            for i in enumerate(inFile):
                counter = counter + 1
                return str(counter) # could be int or w/e else you want it to be
    

    这将计算行数,如果你想去掉一个单词或冒号,它可以很容易地适应这样做。

    【讨论】:

      【解决方案4】:

      只是得到了这样的行数:

      with open(listname) as list:
          lines = len(list.readlines())
      

      【讨论】:

      • 您以后应该更清楚您的问题限制。 “左侧”无关紧要。
      • @aryamccarthy 是的,很抱歉,不过感谢您的帮助!
      猜你喜欢
      • 1970-01-01
      • 2017-02-02
      • 1970-01-01
      • 2023-03-22
      • 2018-05-09
      • 1970-01-01
      • 1970-01-01
      • 2012-01-10
      • 1970-01-01
      相关资源
      最近更新 更多