How to Count the Frequencies of the Letters in User Input

How do I count the frequencies of the letters in user input?

I changed the output a little bit (removed the space before the comma) so that I don't look like uneducated.

puts "Enter string: "
gets.chomp.downcase
.each_char.with_object(Hash.new(0)){|c, h| h[c] += 1}
.sort_by{|_, v| v}
.reverse
.each{|k, v| puts k + ", " + v.to_s + " " + "*" * v}

Output:

Enter string: 
uuuuiiii
i, 4 ****
u, 4 ****

how to count the frequency of letters in text excluding whitespace and numbers?

This should work:

>>> from collections import Counter
>>> from string import ascii_letters
>>> def count_letters(s) :
... filtered = [c for c in s.lower() if c in ascii_letters]
... return Counter(filtered)
...
>>> count_letters('Math is fun! 2+2=4')
Counter({'a': 1, 'f': 1, 'i': 1, 'h': 1, 'm': 1, 'n': 1, 's': 1, 'u': 1, 't': 1})
>>>

How to count the frequency of the two first letters in a word from a dictionary?

The code assumes that the input has one word per line without leading spaces and will count all words that start with two ASCII letters from 'a'..'z'. As the statement in the question is not fully clear, I further assume that the character encoding is ASCII or at least ASCII compatible. (The question states: "there are no accentuated latin characters and they are all accii lowercase")

If you want to include words that consist of only one letter or words that contain ', the calculation of the index values from the characters would be a bit more complicated. In this case I would add a function to calculate the index from the character value.
Also for non-ASCII letters the simple calculation of the array index would not work.

The program reads the input line by line without storing all lines, checks the input as defined above and converts the first two characters from range 'a'..'z' to index values in range 0..'z'-'a' to count the occurrence in a two-dimensional array.

#include <stdio.h>
#include <stdlib.h>

int main (void) {
char *line = NULL;
size_t len = 0;
ssize_t read;

/* Counter array, initialized with 0. The highest possible index will
* be 'z'-'a', so the size in each dimension is 1 more */
unsigned long count['z'-'a'+1]['z'-'a'+1] = {0};

FILE *fp = fopen("large", "r");
if (fp == NULL)
{
return 1;
}

while ((read = getline(&line, &len, fp)) != -1)
{
/* ignore short input */
if(read >= 2)
{
/* ignore other characters */
if((line[0] >= 'a') && (line[0] <= 'z') &&
(line[1] >= 'a') && (line[1] <= 'z'))
{
/* convert first 2 characters to array index range and count */
count[line[0]-'a'][line[1]-'a']++;
}
}
}

fclose(fp);
if (line)
free(line);

/* example output */
for(int i = 'a'-'a'; i <= 'z'-'a'; i++)
{
for(int j = 'a'-'a'; j <= 'z'-'a'; j++)
{
/* only print combinations that actually occurred */
if(count[i][j] > 0)
{
printf("%c%c %lu\n", i+'a', j+'a', count[i][j]);
}
}
}

return 0;
}

The example input

foo
a
foobar
bar
baz
fish
ford

results in

ba 2
fi 1
fo 3

How can I count the number of occurrences in a string based on character letter?

I would build a histogram (frequency) of the letters, then query the histogram:

// Assume ASCII encoding

int main()
{
std::string filename;
std::cout << "Enter filename: ";
std::getline(std::cin, filename);
std::ifstream data_file(filename);
if (!data_file)
{
std::cerr << "Error opening " << filename << "\n";
return 1;
}

// Use 256 entries for ASCII, just to simplify the code
// although ASCII max value is 127.
char frequencies[256] = {0};

// Build histogram / frequencies.
const unsigned int BUFFER_CAPACITY = 1024u * 1024u;
static char buffer[BUFFER_CAPACITY];
std::cout << "Creating histogram ...\n";
while (data_file.read(buffer, BUFFER_CAPACITY))
{
const std::size_t chars_read(data_file.gcount());
for (unsigned int i = 0U; i < chars_read; ++i)
{
const char index = buffer[i];
frequencies[index]++;
}
}
// TBD by O.P.
return 0;
}

The frequency of a given letter is:

unsigned int freq = frequency[letter];

To get the frequency of all the vowels, you could do something like this:

static const char vowels[] = "AEIOUaeiou";
for (unsigned int i = 0; i < (sizeof(vowels) - 1U); ++i)
{
std::cout << vowels[i] << ": " << frequencies[i] << "\n";
}

Counting the frequency of letters of the alphabet in some lines of text

You asked what you did wrong. Well you are very close and you only did two things incorrectly.

  1. This line char[] alphabet = new char[28] should be 26.
  2. Look at the following code from your program.
 for (int i = 0; i < alphabet.length; i++) 
{ frequency = 0 ;
for (int j = 0; j < linesOfText.length(); j++) {
character = linesOfText.charAt(j) ;
if (character == alphabet[i]) {
frequency++ ;
}
}

System.out.println(alphabet[i] + "\t\t" + frequency) ;
i++;
}

In the first loop you increment i using i++
But you also increment it at the end after the print statement. The last one should be
removed.

A few observations

Instead of searching for your character inside an inner loop, just use the character to index into your list and bump the count. For example:

int count[] = new int[26];

say an you find the letter c =='i'.

count[c - 'a']++; ///increments the count for letter i.

Calculating the Character frequency in a String using C

It works fine, but the output may be confusing you!

For the input string "Foo", the output is this:

f occurs 1 times in the entered string.
o occurs 2 times in the entered string.

Lower and uppercase are counted together, so you don't see "F occurs 1 times".

http://ideone.com/ACJnPD

Counting the Frequency of Letters in a string (Python)

You could just check the input with if else and raise an Error if needed with a custom message

if original_input == "":
raise RuntimeError("Empty input")
else:
# Your code goes there

As a side not, input() is enough, no need to add quotes ""

Edit: This question was edited, the original question was to check if an input is empty.

Second edit:

If you want your code to print letters as in your output, you should iterate over your word instead over your alphabet:

for c in word:
print("The letter", c ,"occured", word.count(c), "times")


Related Topics



Leave a reply



Submit