繁体   English   中英

如何编写返回总位数和单个空格的 function

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

嗨,我正在尝试编写一个 function 来打开一个文件并返回它包含的总位数和单个空格。 该代码没有出现错误,但在 doctests 中它返回了错误的数字。

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

我可能会在此处使用 go 作为正则表达式替换选项:

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

这里的逻辑是返回原文长度与去掉所有数字和空格后的长度之差。 这应该对应于文件中的数字和空格字符的数量。

请发布您正在使用的文件的示例,您期望的结果以及您得到的结果。 您可能没有计算isspace中的某些字符。 例如,换行符很重要。 这取决于您要考虑“单个空格”的内容。

下面给出了另一种形式。 您必须将您认为是“空格”的所有字符添加到正则表达式中:

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

参见,例如, https://stackoverflow.com/a/5658439/2707864

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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