gpt4 book ai didi

Python计算文本文件中包含数字的行数

转载 作者:太空宇宙 更新时间:2023-11-04 11:08:54 25 4
gpt4 key购买 nike

假设我有这个文本文件:

some text
120 130
1847 1853
other text
207 220
text
306 350
some other text
400 435
900 121
125 369

我想计算每个字符串后包含数字的行数,这样我的输出就像:

2
1
1
3

这是我尝试过的:

m=0    
with open('some_txt_file.txt','r') as f:
for line in f:
if line.replace(" ","").isdigit():
m+=1
else:
m=0

但这给了我一个错误的结果。我该如何编码?

最佳答案

您唯一缺少的是每一行都以 '\n' 结尾,这破坏了 .isdigit() 测试。让我们使用相同的代码,但只是以 .strip() 结束的行:

m = 0
with open('some_txt_file.txt','r') as f:
for line in f:
if line.strip().replace(" ", "").isdigit():
m += 1
else:
if m: print(m)
m = 0
if m: print(m)

# prints:
# 2
# 1
# 1
# 3

关于Python计算文本文件中包含数字的行数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58767830/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com