1

我需要创建一个函数来打开一个文本文件并打印其中包含特定字符的行。之后,我需要它来打印该字符在整个文本文档中出现的次数。我开发了一个函数来计算一个字符在字符串中出现的次数。这里是:

    def countLetterString(char, str):
       if str == "":
          return 0
       elif str[0] == char:
           return 1 + countLetterString(char, str[1:])
       else:
           return countLetterString(char, str[1:])  

我想要做的功能是:

    def countLetterString(char, Textfilename):

它需要一个给定的字符打开一个文件并使用 for 循环打印包含该字符的行。我完全被难住了:(

4

4 回答 4

3

Python 在可迭代对象上有一个 count 方法(可以将字符串视为可迭代对象)

char = 'b'
count = 0

f = open('textfile.txt', 'r')

for line in f:
    if char in line:
        print line
        count += line.count(char)

print count
f.close()
于 2013-09-27T18:33:54.347 回答
1
#!/usr/bin/env python
'''
Usage:
./charinfile.py myfilename char
'''
import sys

filename = sys.argv[1]
charac = sys.argv[2]
count=0

with open(filename,"r") as f:

    for line in f:
        count = count + line.count(charac)

print "char count is %s" % count            
于 2013-09-27T18:44:49.377 回答
0

在我看来,递归不是最好的解决方案,你可以迭代循环

def readCharacters(character,filename):
    f = open('filename','r')
    counter = 0
    for line in f.readlines():

        if character in line:
            print line
        for character in line:
            counter = counter + 1

    return counter

    f.close()
于 2013-09-27T18:33:37.380 回答
0

这是一种方法:

with open(filename, "r") as f:    # opens the file `filename` and allows it to be referenced with the name `f`
    counter = 0                   # initializes the counter of the character as 0
    for line in f:                # (you can iterate directly over files) 
        if character in line:     
            print(line)
            counter += line.count(character)

最好使用with语句打开文件,因为这意味着无论发生什么情况都会关闭它(例如,即使在管理文件时发生异常)。

据我了解,您的代码与该问题似乎没有多大意义,但这似乎最像您想要的:

def countLetterString(char, string):
   if string == "":
      return None   # explicit to be clear
   else:
       return string.count(char)

with open(filename, "r") as f:
    counter = 0
    for line in f:
        count = countLetterString(the_character, line)
        if count:
            print(line)
            counter += count

如果你正在寻找一个递归解决方案(你可能不是):

def count_and_print(file_object, character):
    def do_line(file, counter):
        line = file.readline()
        if line:
            if character in line:
                print(line)
                return do_line(file, counter + line.count(character))
        else:
            return counter
    return do_line(file_object, 0)
于 2013-09-27T18:36:16.927 回答