簡體   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