簡體   English   中英

(Python)使用for循環在文本文件中打印重復出現的字符

[英](Python) Using a for loop to print reoccurring characters in a text file

我需要創建一個打開文本文件的函數,並打印出包含特定字符的行。 之后,我需要它來打印整個文本文檔中該字符的次數。 我開發了一個函數來計算一個字符在字符串中出現的次數。 這里是:

    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循環打印其中包含該字符的行。 我完全被難倒了:(

Python在iterables上有一個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()
#!/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            

在我看來,遞歸不是最好的解決方案,你可以迭代循環

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()

這是一種方法:

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM