【问题标题】:How to count how many times two words occur in a text file in Python?如何计算 Python 文本文件中两个单词出现的次数?
【发布时间】:2013-03-20 00:19:46
【问题描述】:

我有一个名为 dogs.txt 的文本文件,其中包含以下几行。

'#'颜色体毛类型

白色大硬保守

黄色大硬保守

棕色大号软暴力

黄大软保守

棕色小硬保守

棕色小硬保守

白色小硬保守

黄小软暴力

黄色小硬暴力

棕色大硬保守

白大软保守

黄小软暴力

棕色小软保守

棕色大硬暴力

棕色小硬保守

黄色小硬暴力

每一行代表一只狗。当人员输入 dogs.txt 时,我希望输出显示两件事。

  1. 有几只狗?检查

  2. 有多少条狗是黄色和暴力的?

输出会告诉你有 16 条狗。

接下来我需要做的是找出这 16 条狗中有多少是黄色和暴力的。我一直坚持如何做到这一点。我想我将不得不使用 infile.read() 但我不确定如何。请大家帮忙。

【问题讨论】:

  • 你是在使用line.strip()来检查该行是否为空吗?
  • @Adam Obeng 是的,我正在使用 line.strip() 检查该行是否为空
  • 您的代码的问题是num_yellow_and_violent =+1=+1 的意思是“将变量设置为值+1。你想要+= 1
  • @abarnert 非常感谢。那就是缺少的东西:)

标签: python file text count


【解决方案1】:

这里有一个快速检查黄色和暴力号码的方法:

with open('dogs.txt') as f:
    f.readline() # Skip first line
    print sum({'yellow','violent'}.issubset(line.split()) for line in f)

但是,当我添加行号检查时,它并不那么优雅

with open('dogs.txt') as f:
    f.readline() # Skip first line
    i, num_dogs = 0, 0
    for line in f:
        num_dogs += {'yellow','violent'}.issubset(line.split())
        i += 1
    print i, num_dogs

【讨论】:

    【解决方案2】:
    yellow_and_violent = 0    
    for line in infile:
        if line.strip() and line[0]!='#':               
            lines+=1
        if ('yellow' in line) and ('violent' in line'):
            yellow_and_violent += 1
    

    还有一些事情:

    • 您可以引发自定义异常
    • ,而不是将变量设置为在找不到文件时不对其进行分析
    • 你不应该使用类名作为变量名(例如file

    这给出了:

    import os.path
    
    filename = input("Enter name of input file >")
    try:
        infile = open(filename, "r")
    except IOError:
        raise Exception("Error opening file '%s', analysis will not continue" % filename)
    
    dogs = 0
    yellow_and_violent = 0
    
    for line in infile:
        if line.strip() and line[0]!='#':               
            dogs += 1
        if ('yellow' in line) and ('violent' in line):
           yellow_and_violent += 1
    print("Total dogs =",dogs)
    print("Yellow and violent dogs = ", yellow_and_violent)
    

    【讨论】:

    • 你的黄色和暴力答案每次都给 0。
    • 应该是yellow_and_violent += 1,在倒数第二行。此外,您的if 末尾还有一个额外的'
    • @nbrooks,谢谢。这就是我不喜欢自增运算符的原因。
    • 它是 yellow_and_violent += 1,我把 ' 拿出来,但它仍然给了 16 条狗,但它总是打印 0 黄色和暴力。
    • @Jett:应该只有一个for line in infile 循环,因为一旦你遍历文件对象一次,就没有剩下的行了
    【解决方案3】:

    使用正则表达式:

    import os.path
    import sys 
    import re
    reg = re.compile("^yellow.*violent")
    try:
        file=sys.argv[1]
        infile=open(file,"r")
    except IOError:
          raise Exception("open '%s' failed" % filename)
    lines=0
    yv=0
    for line in infile:
      if line.strip() and line[0]!='#':
        lines+=1
        if reg.match(line):
          yv+=1
    print("Total dogs =",lines)
    print("Total yv dogs =",yv)
    

    【讨论】:

    • @Kay,你能详细说明你的评论吗?
    • 这个问题很简单。我只会推荐正则表达式作为最后的手段。这不是你应该使用正则表达式的问题……
    • 这是为什么呢?他们慢吗?
    • 我在 file=sys.argv[1] 中使用这个程序时出错,说列表索引超出范围
    • @Jett,是的,您需要指定文件名:python sc.py input
    【解决方案4】:
    dog_counter = 0
    yellow_and_violent = 0
    with open('dog.txt', 'r') as fd:
        for line in fd.readlines():
            if line.startswith("'#'") or (not line.strip()):
                continue
            dog_counter += 1
            if ('yellow' in line) and ('violent' in line):
                yellow_and_violent += 1
    print("Total dogs: %d" % dog_counter)
    print("yellow and violent dogs: %d" % yellow_and_violent)
    

    【讨论】:

      猜你喜欢
      • 2018-08-25
      • 1970-01-01
      • 1970-01-01
      • 2023-03-29
      • 1970-01-01
      • 2012-12-08
      • 1970-01-01
      • 2017-08-14
      相关资源
      最近更新 更多