gpt4 book ai didi

c - 如何从字典中计算单词中两个首字母的频率?

转载 作者:行者123 更新时间:2023-12-04 14:53:46 25 4
gpt4 key购买 nike

我有一个 143k 的小写单词词典,我想计算前两个字母的出现频率
(即: aa* = 14, ab* = 534, ac = 714 ... za = 65, ... zz = 0 )并将其放入二维数组中。
然而,我不知道如何在没有开关或一堆 if else 的情况下迭代它们,我尝试在谷歌上寻找解决方案,但我只能找到整个单词中的字母数量,而且主要是python中的东西。
我坐在这里有一段时间想我怎么能做到这一点,我的大脑一直在阻止这是我想出的,但我真的不知道该往哪里去。

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

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

int i = 0;
while ((read = getline(&line, &len, fp)) != -1)
{
arr[i] = line;
i++;
}

char c1 = 'a';
char c2 = 'a';
i = 0;
int j = 0;
while (c1 <= 'z')
{
while (arr[k][0] == c1)
{
while (arr[k][1] == c2)
{

}
c2++;
}
c1++;
}
fclose(fp);
if (line)
free(line);
return 0;
}
我是白痴还是我只是错过了一些非常基本的东西?我该如何解决这个问题?
编辑:我忘了提到字典只是小写,并且有一些边缘情况,比如 ae有些词有 ' (如 e'ere's )没有重音拉丁字符,它们都是小写字母

最佳答案

该代码假定输入每行一个单词,没有前导空格,并将计算以来自 'a' 的两个 ASCII 字母开头的所有单词。 .. 'z' .由于问题中的陈述并不完全清楚,我进一步假设字符编码是 ASCII 或至少是 ASCII 兼容的。 (问题说明:“没有重读的拉丁字符,它们都是小写的”)
如果要包含仅由一个字母组成的单词或包含 ' 的单词,从字符计算索引值会更复杂一些。在这种情况下,我将添加一个函数来计算字符值的索引。
同样对于非 ASCII 字母,数组索引的简单计算将不起作用。
程序逐行读取输入而不存储所有行,检查上述定义的输入并转换范围 'a' 中的前两个字符。 .. 'z'索引范围内的值 0 .. 'z'-'a'计算二维数组中的出现次数。

#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;
}
示例输入
foo
a
foobar
bar
baz
fish
ford
结果是
ba 2
fi 1
fo 3

关于c - 如何从字典中计算单词中两个首字母的频率?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68564322/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com