Python Character Count Output

Asked 2 years ago, Updated 2 years ago, 18 views

import urllib.request

infile = urllib.request.urlopen("http://www.yahoo.com/index.html") f = infile.read().decode().split()

freqs ={}

for line in f: for char in line.strip(): if char in freqs: freqs[char] += 1 else: freqs[char] = 1

freqs_list = freqs.keys()

for char in freqs_list: print( char, freqs[char] )

In this way, the number of characters with char type is found and counted I want to use this to find the number of alphabets, count them, and print them out It's not going as I wanted. freqs[char] => I think I need to change this part, so I want to ask for your help!

python

2022-09-22 19:03

2 Answers

I think you want to know how many times each alphabet is repeated on http://www.yahoo.com/index.html site. I think you can use regular expressions and Counter classes.

import urllib.request
import re
import collections

infile = urllib.request.urlopen("http://www.yahoo.com/index.html")
f = infile.read().decode().split()

regex = re.compile(r"[a-zA-Z]") # Regular expression for extracting the alphabet
letters = ''.join(f) # To apply the regular expression, the element of list f is connected to the string
all_matches = regex.foundall(letters) # Found all alphabets from letters

counter = collections.Counter(all_matches) #collections.Counter class to count each alphabet

print(counter)


2022-09-22 19:03

import urllib.request

infile = urllib.request.urlopen("http://www.yahoo.com/index.html")
f = infile.read().decode().split()
letters = ''.join(f) # Connect the element of f to string in order to iterate at once

answer = {}
for i in letters:
    if i in 'qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM':
        try:
            answer[i] += 1
        except:
           answer[i] = 1
print(answer)
import urllib.request

infile = urllib.request.urlopen("http://www.yahoo.com/index.html")
f = infile.read().decode().split()
letters = ''.join(f) # Connect the element of f to string in order to iterate at once

answer = {}
for i in letters:
    if i in 'qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM':
        if i in answer:
            answer[i] += 1
        else:
           answer[i] = 1
print(answer)

You can fill it out.


2022-09-22 19:03

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.