-
Notifications
You must be signed in to change notification settings - Fork 0
/
Week6-LetterFreq
87 lines (59 loc) · 1.86 KB
/
Week6-LetterFreq
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#sol. in python
import numpy as np
def letterFrequency(filename):
# Computes the frequency of each letter, a to z, case insensitive
# in the text file (filename given as input)
# Define alphabet
alphabet = "abcdefghijklmnopqrstuvwxyz"
# Read file into string
filein = open(filename, "r")
lines = filein.readlines()
text = "".join(lines)
# Convert to lower case
text = text.lower()
# Compute number of occurencies
occur = np.zeros(26)
for i in range(26):
occur[i] = text.count(alphabet[i])
# Compute frequencies in percent
freq = occur / np.sum(occur) * 100
return freq
#sol. in matlab
function freq = letterFrequency(filename)
% Computes the frequency of each letter, a to z, case insensitive
% in the text file (filename given as input)
% Define alphabet
alphabet = 'abcdefghijklmnopqrstuvwxyz';
% Read file into string
text = fileread(filename);
% Convert to lower case
text = lower(text);
% Compute number of occurencies
occur = zeros(1, 26);
for i = 1:26
occur(i) = sum(text == alphabet(i));
end
% Compute frequencies in percent
freq = occur / sum(occur) * 100;
#sol. in R
letterFrequency <- function(filename) {
# Computes the frequency of each letter, a to z, case insensitive
# in the text file (filename given as input)
# Define alphabet
alphabet <- "abcdefghijklmnopqrstuvwxyz"
# Read file into string
lines <- readLines(filename)
text <- paste0(lines, collapse="")
# Convert to lower case
text <- tolower(text)
# Convert string to character vector
textvec <- strsplit(text, "")[[1]]
# Compute number of occurencies
occur <- rep(0, 26)
for (i in 1:26) {
occur[i] <- sum(textvec == substring(alphabet, i, i))
}
# Compute frequencies in percent
freq <- occur / sum(occur) * 100
return(freq)
}