如何计算一个数字出现在文件中每个数字开头的次数?(python)

如何计算一个数字出现在文件中每个数字开头的次数?(python),python,Python,我试图计算文件中每个数字开头出现1、2、3、…、9的次数。我的代码是这样的: DECIMAL_NUM='123456789' def main(): #get the file name from the user file_name=str(input("Enter a file name: ")) #open the file to read input_file= open(str(file_name),'r') #reads the first

我试图计算文件中每个数字开头出现1、2、3、…、9的次数。我的代码是这样的:

DECIMAL_NUM='123456789'

def main():
    #get the file name from the user
    file_name=str(input("Enter a file name: "))

    #open the file to read
    input_file= open(str(file_name),'r')
    #reads the first line of the file
    line=input_file.readline().strip()

    one=0
    two=0
    three=0
    four=0
    five=0
    six=0
    seven=0
    eight=0
    nine=0
    i=0

    while line!="":

        if line[0]==DECIMAL_NUM[0]:
            one+=1            
        elif line[0]==DECIMAL_NUM[1]:
            two+=1
        elif line[0]==DECIMAL_NUM[2]:
            three+=1
        elif line[0]==DECIMAL_NUM[3]:
            four+=1
        elif line[0]==DECIMAL_NUM[4]:
            five+=1
        elif line[0]==DECIMAL_NUM[5]:
            six+=1
        elif line[0]==DECIMAL_NUM[6]:
            seven+=1
        elif line[0]==DECIMAL_NUM[7]:
            eight+=1
        elif line[0]==DECIMAL_NUM[8]:
            nine+=1           
        line=input_file.readline().strip()
        i+=1
    input_file.close()
    print(one)
    print(two)    
main()
我也在计算文件中有多少个数字,这样我就可以计算出每个数字出现的百分比。我觉得我的代码有点冗长,可能有更好的方法。输入文件具有以下编号:

1292

1076

188040

1579

3510

2597

3783

64690

出于某种原因,我得到了1作为1出现的次数,而它应该是5。谁能给我一些指点吗?谢谢

以下是完成此任务的一种方法:

# Get non-empty lines from input file:
relevant_lines = [line for line in open(file_name).readlines() if line.strip()]
# Count them:
num_lines = len(relevant_lines)

import defaultdict
# If a key does not exist in a defaultdict when adding a value for it,
# it will be added with a default value for the given data type
# (0 in case of int):
d = defaultdict(int)

# Iterate through lines; get first character of line
# and increment counter for this character by one in defaultdict:
for line in relevant_lines:
    d[line[0]] += 1

# Print results:
for key, value in d.items():
    print(k + ' appears ' + value + ' times in file.')
如果您不允许使用
dict
s,以下是修复代码的方法:

DECIMAL_NUM='123456789'

def main():
    # Get file name from user
    file_name = input("Enter a file name: ")

    # Open the file to read, and get a list of all lines:
    lines = open(file_name, 'r').readlines()

    one = 0
    two = 0
    three = 0
    four = 0
    five = 0
    six = 0
    seven = 0
    eight = 0
    nine = 0

    for line in lines:

        if line.strip(): # Check if line is not empty

            if line[0] == DECIMAL_NUM[0]:
                one += 1            
            elif line[0] == DECIMAL_NUM[1]:
                two += 1
            elif line[0] == DECIMAL_NUM[2]:
                three += 1
            elif line[0] == DECIMAL_NUM[3]:
                four += 1
            elif line[0] == DECIMAL_NUM[4]:
                five += 1
            elif line[0] == DECIMAL_NUM[5]:
                six += 1
            elif line[0] == DECIMAL_NUM[6]:
                seven += 1
            elif line[0] == DECIMAL_NUM[7]:
                eight += 1
            elif line[0] == DECIMAL_NUM[8]:
                nine += 1

    print(one)
    print(two)

main()

你的代码很好。问题出在你的数据文件上。删除空白行,程序应该给你正确的结果。

1292
1076
188040
1579
3510
2597
3783
64690

处理第一行后,将读取下一行。但这是一个空行,while循环结束。

好的行[0]是第一个字符,十进制数[0]=1。因此,计算1在行的开头出现的次数。不是吗?输入文件有空行吗?嗯,我复制并粘贴了它,txt文件中有很多空白。因此,可能会有空行。但不确定如何找到它。@cobra您可以通过调用一行上的
.strip()
(这将删除其中的所有空白,包括换行符和制表符),然后通过
if line.strip():…
检查结果是否计算为
False
。如果行为空(
),此检查将返回
False
@cobra请记住这一点,并再次查看循环。您的解决方案可能是正确的。但是,我还没有完成dict(我假设它是字典)。所以,不能使用它。@cobra检查我的更新答案,我已经根据你的想法提供了一个解决方案。非常感谢。我确实检查过了,它给出了正确的答案。我需要做更多的工作。再次感谢您解决我的问题。@cobra不客气。如果你解决了你的问题,你可能会考虑接受我的答案:)同时,如果你对我发布的解决方案有任何疑问,请告诉我。我很乐意为我的帖子添加更多信息。@cobra也,+1表示“我需要做更多的工作。”这就是精神所在!;)你是对的。我没有复制和粘贴,而是创建了一个具有相同名称和数据的新文件,我的代码给出了更好的答案。非常感谢你和我一起工作。“更好的答案”?我运行了你的代码,对我来说似乎很好。你还有什么问题?我也在学习Python,它给出了正确的答案。以前,我把我所有的数字都列在一列,这就是为什么所有的问题都发生了。原始文件中的所有数字都在一行中,现在一切正常。谢谢你的帮助。