计数每个lin的整数数

2024-05-03 09:27:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我想了解如何计算每行整数的数目。到目前为止,我有以下几点:

import sys

filename = raw_input("Enter Filename: ")

names_list = []
with open(filename, 'r') as file:
    for line in file:
        line = line.strip()
        if line:
         if not line.startswith("#"):       
            names_list.append(line)    

with open(filename, 'r') as file:
    for line in file.readlines():
        words = len(line.split(' '))
        print words

输出为:

Enter Filename: somenumbers.txt
6
9
4
1
5
5
5
5
1
5
1
1
5
20

输出应为:

Enter Filename: somenumbers.txt
9
4
5
5
5
1
20

有没有关于我计算每行整数的错误建议?非常感谢。你知道吗

编辑: 更改为strip()时,输出不正确。似乎从6的输出开始,每秒钟都不打印一个整数。这些附加值(a6,1,5,5,5)从何而来?如何避免这些额外的错误值?(目前为止谢谢大家)


Tags: inforifnamesaswithline整数
3条回答

使用words = len(line.split(' '))而不是words = len(line.strip(' '))。你知道吗

更新:

使用以下命令代替第二次打开文件: for name in names_list:

更新2:

您可以通过以下方法进一步简化:

with open(filename, 'r') as file:
    for line in file:
        print(len(line.strip().split()))

更新
循环浏览文件内容两次:

with open(filename, 'r') as file:
    #...  

with open(filename, 'r') as file:
    #...

第一次将所有“有效”行添加到数组时,即names_list(为什么是这个标识符?)。第二次只需打印每行中的字数,而不考虑其有效性。只需循环一次。你知道吗

with open(filename, 'r') as file:
    for line in file:
        if line.strip() and not line.startswith("#"):
            names_list.append(line)
            print "There are ", len(line.split()), " numbers on this line"

你想要的是split。你知道吗

this answer。你知道吗

假设每行非#行上只包含整数,只需将其拆分并计算“字数”。你知道吗

#after checking the line is valid
print "This line contains", len(line.split()), "numbers"

我想你是说^{}而不是^{}。替换:

words = len(line.strip(' '))

使用:

words = len(line.split())

相关问题 更多 >