简体   繁体   English

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

[英]How to count the number of times a digit appears at the beginning of each number in a file? (python)

I am trying to count the number of times 1,2,3,...,9 appear at the beginning of each number in a file. 我正在尝试计算1,2,3,...,9在文件中每个数字开头出现的次数。 This is how my code goes: 这是我的代码的样子:

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()

I am also counting how many numbers are there in the file, so that I can calculate percentage of appearance of each digit. 我还要计算文件中有多少个数字,以便可以计算每个数字出现的百分比。 I think my codes are a little bit wordy and there might be a better way to do it. 我认为我的代码有点罗word,可能会有更好的方法来做到这一点。 The input file has the following numbers: 输入文件具有以下数字:

1292

1076

188040

1579

3510

2597

3783

64690

For some reason, I am getting the number of times 1 is appearing as 1, when it should be 5. Could someone please give me some pointers? 由于某种原因,我得到1出现为1的次数,应该为5。有人可以给我一些指示吗? Thanks 谢谢

Here is one way of approaching this task: 这是完成此任务的一种方法:

# 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.')

If you are not allowed to use dict s, here's how to fix your code: 如果不允许使用dict ,则以下是修复代码的方法:

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()

You code is fine. 您的代码很好。 It's your data file that's giving you problem. 是您的数据文件给您带来了麻烦。 Remove the blank lines and your program should give you the right results. 删除空白行,您的程序应该给您正确的结果。

1292
1076
188040
1579
3510
2597
3783
64690

After you processed the first line, the next line is read. 处理第一行后,将读取下一行。 But that's a blank line and your while loop ends. 但这是空白行,而while循环结束。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 计算每个成绩在文件中出现的次数 - Count Number of times each grade appears in a file 如何计算一个单词出现在 csv 文件的每一行中的次数,在 python 中 - How to count the number of times a word appears in each row of a csv file, in python 计算每个符号出现在字符串中的次数 - python - Count the number of times each of the symbols appears in a string - python 如何计算键的每个值出现的次数? - How do I count the number of times each value appears for a key? 如何使用.count计算一个列表中每个项目出现在python中另一个列表中的次数? - How to use .count to calculate number of times each item in one list appears in another list in python? 如何计算每个单词在 txt 文件中出现的次数? - How can I count the number of times each word appears in a txt file? Python,查找每个令牌出现在给定文件中的次数 - Python, Finding the number of times each token appears in a given file 如何使用python计算字母在单词中出现的次数 - How count the number of times a letter appears in word using python 如何使用 python 计算特定字段的单词出现次数? - How to count the number of times a word appears for specific fields using python? 如何计算一个值在python的嵌套字典中出现的次数? - How to count number of times a value appears in nested dictionary in python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM