简体   繁体   中英

How to write a function which returns the total number of digits and single spaces

Hi im trying to write a function that opens a file and returns the total number of digits and single spaces it contains. The code isn't coming up with an error but in the doctests it is returning the wrong number.

def digit_space_count(filename):
    file_in = open(filename)
    text = file_in.read()
    count = 0
    for ch in text:
        if ch.isspace():
            count += 1
        if ch.isdigit():
            count += 1
    file_in.close()
    return count

I might go for a regex replacement option here:

def digit_space_count(filename):
    with open(filename, 'r') as the_file:
        text = the_file.read()

        return len(text) - len(re.sub(r'[0-9 ]', '', text))

The logic here is to return the difference between the length of the original text, and the length after removing all digits and spaces. This should correspond to the number of digit and space characters in the file.

Please post an example of the file you are using, the result you expect, and what you get. You are possibly not counting some characters in isspace . For instance, newlines count for that. It depends on what you want to consider for "single spaces".

An alternative form is given below. You have to add to the regular expression all characters that you consider "spaces":

def digit_space_count(filename):
    import re
    file_in = open(filename)
    text = file_in.read()
    count = len(text) - len(re.sub(r"[ 0-9]", "", text))
    file_in.close()
    return count

See, eg, https://stackoverflow.com/a/5658439/2707864

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM