【发布时间】:2018-08-11 22:51:26
【问题描述】:
我按照改进的 Lansky 算法实现了简单的音节化算法,但是当我需要在超过 200 万个单词的语料库上运行这个算法时,它真的很慢。有人可以指出导致它如此缓慢的方向吗?下面的算法:
最后一个元音(元音组)之后的一切都属于最后一个音节
第一个元音(元音组)之前的一切都属于第一个音节
如果元音之间的辅音个数是偶数(2n),则将它们分为 前半部分属于左元音,后半部分属于右元音 (n/n)。
如果元音之间的辅音数量是奇数(2n + 1),我们将它们分为 n / n + 1 份。
-
如果元音之间只有一个辅音,则属于左元音。
#include <stdio.h> #include <string.h> #define VOWELS "aeiou" int get_n_consonant_between(char *word, int length) { int count = 0; int i = 0; while (i++ < length) { if (strchr(VOWELS, *word)) break; word++; count++; } return count; } void syllabification(char *word, int n_vowel_groups) { int i = 0, length = strlen(word), consonants; int syllables = 0, vowel_group = 0, syl_length = 0; char *syllable = word; char hola[length]; memset(hola, 0, length); if (n_vowel_groups < 2) { printf("CAN'T BE SPLIT INTO SYLLABLES\n\n"); return; } while (i < length) { if (strchr(VOWELS, word[i])) { syl_length++; i++; if (vowel_group) continue; vowel_group = 1; } else { if (vowel_group) { consonants = get_n_consonant_between(word + i, length - i); if (consonants == 1) { // printf("only one consonant\n"); syl_length++; strncpy(hola, syllable, syl_length); i++; } else { int count = consonants / 2; if ((consonants % 2) == 0) { /* number of consonants is 2n, first half belongs to the left vowel */ syl_length += count; } else { syl_length += count; } strncpy(hola, syllable, syl_length); i += count; } syllables++; if (syllables == n_vowel_groups) { printf("syllable done %d: %s\n", syllables, syllable); break; } printf("syllable %d: %s\n", syllables, hola); syllable = word + i; syl_length = 0; memset(hola, 0, length); } else { syl_length++; i++; } vowel_group = 0; } } } int count_vowel_groups(char *word) { int i, nvowels = 0; int vowel_group = 0; for (i = 0; i < strlen(word); i++) { if (strchr(VOWELS, word[i])) { if (vowel_group) continue; vowel_group = 1; } else { if (vowel_group) nvowels++; vowel_group = 0; } } // printf("%d vowel groups\n", nvowels); return nvowels; } void repl() { char *line = NULL; size_t len = 0; int i = 0; int count; FILE *file = fopen("../syllables.txt", "r"); while(i++ < 15) { getline(&line, &len, file); printf("\n\n%s\n", line); count = count_vowel_groups(line); syllabification(line, count); } } int main(int argc, char *argv[]) { // printf("Syllabification test:\n"); repl(); }`
【问题讨论】:
-
这可能属于Code Review,但基本上我会说你最好的选择是避免多次扫描输入(为什么你需要在开始时计算元音组的数量,因为例如?)并找到一种更快的方法来识别元音,例如查找表甚至是简单的 bithack。
标签: c algorithm performance nlp