Count all alphanumeric characters in python text

Asked 2 years ago, Updated 2 years ago, 16 views

Count of all alphabets in a text file

fname=input('Enter a filename:')

fhand=open(fname)

char=list(fhand)

for w in ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']:    
    print(char.count(w))

Text file contents: hello, Jenny

It's all zero. What's wrong?

python

2022-09-22 18:50

1 Answers

There is an easier way to simply leak the alphabet from a file, but answer the questions faithfully.

char=list(fhand)

In , char lines are stored.

For example, if the contents of the file are as follows

abcd
efgh
ijkl

char is ['abcd\n', 'efgh\n', 'ijkl\n'].

Of course, we compare abcd with the alphabet, so there's no case where it's correct.

char[0].count('a') #1

You have to do it with

I think he's a student.In programming, there is no unit called string.

Linear set of characters (end null\0) is a string.

And...

Rather than writing down how to make a list from a to z,

import string
[c for c in string.ascii_lowercase]

Or

[chr(i) for i in range(ord('a'), ord('z') + 1)]

I can make it like that.


2022-09-22 18:50

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.