find the number of occurrence of letter in a txt file using python

前端 未结 2 1231
醉酒成梦
醉酒成梦 2021-01-29 11:44

I need to read the letter from a .txt file and print the number of occurrence in txt file. so far i have been able to print the content in one line but having issue with the cou

相关标签:
2条回答
  • 2021-01-29 11:46

    Here you go. Hopefully your professor will ask you to explain your work.

    grades = open('grades.txt').read().split()
    for grade in sorted(set(grades),
                        key=lambda x: ord(x[0])*3-('+'in x)+('-'in x)):
        print ('{} students got {}'.format(grades.count(grade), grade))
    
    0 讨论(0)
  • 2021-01-29 11:48

    You can use collections.Counter for this

    with open('grades.txt') as f:
        print(Counter(f.read()))
    

    Example

    this is a test that has letters

    Output

    Counter({'t': 7,
             ' ': 6,
             's': 5,
             'a': 3,
             'h': 3,
             'e': 3,
             'i': 2,
             'l': 1,
             'r': 1})
    

    Or to only include letters

    from string import ascii_letters
    with open('grades.txt') as f:
        print(Counter(i for i in f.read() if i in ascii_letters))
    

    Edit
    Without the use of any other libraries, the manual way to do the same thing as above:

    from string import ascii_letters
    d = {}
    with open('grades.txt') as f:
        for letter in d.read():
            if letter in ascii_letters:
                if letter in d:
                    d[letter] += 1
                else:
                    d[letter] = 1
    

    If your file looks something like

    A A+ B B- B B+ B+ A A- B+

    Then the modification to the above code would be

    d = {}
    with open('grades.txt') as f:
        for grade in d.read().split():
            if grade in d:
                d[grade] += 1
            else:
                d[grade] = 1
    
    0 讨论(0)
提交回复
热议问题