[英]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.嗨,我正在尝试编写一个 function 来打开一个文件并返回它包含的总位数和单个空格。 The code isn't coming up with an error but in the doctests it is returning the wrong number.
该代码没有出现错误,但在 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
I might go for a regex replacement option here:我可能会在此处使用 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))
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
.您可能没有计算
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参见,例如, https://stackoverflow.com/a/5658439/2707864
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.