// Структура для хранения звуковых соответствий
typedef struct {
gchar *sound1;
gchar *sound2;
} SoundCorrespondence;
// Функции для сравнения слов и формирования результата
GArray* find_sound_correspondences(const gchar *word1, const gchar word2);
gchar format_correspondences(GArray *correspondences, const gchar *language1, const gchar *language2);
// Функции для работы с файлами звуковых соответствий
void load_sound_correspondences(const gchar *filename);
void free_sound_correspondences();
// Функция для освобождения памяти массива соответствий
void free_sound_correspondences() {
if (correspondences_array != NULL) {
for (guint i = 0; i < correspondences_array->len; i++) {
SoundCorrespondence sc = g_array_index(correspondences_array, SoundCorrespondence, i);
g_free(sc.sound1);
g_free(sc.sound2);
}
g_array_free(correspondences_array, TRUE);
correspondences_array = NULL;
}
}
Assistant
// Функция для разбивки слова на звуки (предполагается посимвольная разбивка)
GArray* split_word_into_sounds(const gchar *word) {
GArray *sounds = g_array_new(FALSE, FALSE, sizeof(gchar *));
const gchar *p = word;
code
while (*p) {
gunichar c = g_utf8_get_char(p);
int char_len = g_unichar_to_utf8(c, NULL);
gchar *sound = g_utf8_substring(p, 0, 1);
g_array_append_val(sounds, sound);
p = g_utf8_next_char(p);
}
return sounds;
}
// Функция для освобождения памяти массива звуков
void free_sounds_array(GArray *sounds) {
for (guint i = 0; i < sounds->len; i++) {
gchar *sound = g_array_index(sounds, gchar *, i);
g_free(sound);
}
g_array_free(sounds, TRUE);
}
// Функция для поиска звуковых соответствий между двумя словами
GArray* find_sound_correspondences(const gchar *word1, const gchar *word2) {
GArray *result = g_array_new(FALSE, FALSE, sizeof(SoundCorrespondence));
code
GArray *sounds1 = split_word_into_sounds(word1);
GArray *sounds2 = split_word_into_sounds(word2);
guint len = MIN(sounds1->len, sounds2->len);
for (guint i = 0; i < len; i++) {
gchar *sound1 = g_array_index(sounds1, gchar *, i);
gchar *sound2 = g_array_index(sounds2, gchar *, i);
// Если звуки идентичны
if (g_strcmp0(sound1, sound2) == 0) {
// Добавляем в результат как одинаковый звук
SoundCorrespondence sc = { g_strdup(sound1), g_strdup(sound2) };
g_array_append_val(result, sc);
} else if (correspondences_array != NULL) {
// Проверяем, есть ли данная пара в списке соответствий
for (guint j = 0; j < correspondences_array->len; j++) {
SoundCorrespondence corr = g_array_index(correspondences_array, SoundCorrespondence, j);
if ((g_strcmp0(sound1, corr.sound1) == 0 && g_strcmp0(sound2, corr.sound2) == 0) ||
(g_strcmp0(sound1, corr.sound2) == 0 && g_strcmp0(sound2, corr.sound1) == 0)) {
SoundCorrespondence sc = { g_strdup(sound1), g_strdup(sound2) };
g_array_append_val(result, sc);
break;
}
}
}
}
free_sounds_array(sounds1);
free_sounds_array(sounds2);
return result;
}
// Функция для формирования строки с результатами
gchar* format_correspondences(GArray *correspondences, const gchar *language1, const gchar *language2) {
GString *result = g_string_new("");
code
if (correspondences->len == 0) {
g_string_append(result, "Звуковые соответствия не обнаружены.");
} else {
for (guint i = 0; i < correspondences->len; i++) {
SoundCorrespondence sc = g_array_index(correspondences, SoundCorrespondence, i);
if (g_strcmp0(sc.sound1, sc.sound2) == 0) {
// Идентичные звуки
gchar *line = g_strdup_printf("В %s и %s одинаковый звук: /%s/.\n", language1, language2, sc.sound1);
g_string_append(result, line);
g_free(line);
} else {
// Различные звуки с соответствием
gchar *line = g_strdup_printf("Вероятные звуковые соответствия в %s и %s: /%s/ и /%s/.\n", language1, language2, sc.sound1, sc.sound2);
g_string_append(result, line);
g_free(line);
}
g_free(sc.sound1);
g_free(sc.sound2);
}
}
g_array_free(correspondences, TRUE);
gchar *final_result = result->str;
g_string_free(result, FALSE);
return final_result;
Проанализируй этот код, сделай интерфейс программы более симетричным, добавь возможность добавлять колонку с языком для сравнения, добавь возможность сравнивать несколько взаимозаменяемых звуков из таблицы csv, а не только 2 звука. Расширь таблицу csv новыми возможными звуковыми соответствиями из расширенной латиници и МФА. Напиши полную обновленную версию всех файлов
Sure! Let's make the necessary modifications to your code to satisfy the requirements. We'll:
Update the CSV parser to handle multiple sounds in a group, not just pairs.
Implement a Union-Find data structure to manage groups of interchangeable sounds.
Modify the GUI to be more symmetrical and allow adding columns for additional languages and words.
Adjust the comparison function to compare sounds across multiple languages.
Expand the CSV sound correspondence table with new sound correspondences from extended Latin and IPA.
Below is the updated code for all the files, integrating these changes.
Updated sound_correspondences.csv:
We've expanded the CSV file to include groups of sounds that correspond, including sounds from extended Latin and IPA alphabets.
We've updated the header file to adjust function signatures and include the new data structures for the Union-Find implementation.
c
// compare.h
#ifndef COMPARE_H
#define COMPARE_H
#include <glib.h>
// Union-Find Node for sounds
typedef struct UFNode {
gchar *sound;
struct UFNode *parent;
} UFNode;
// Functions for comparing words and forming the result
GArray* find_sound_correspondences(GPtrArray *words);
gchar* format_correspondences(GArray *correspondences, GPtrArray *languages);
// Functions for working with the sound correspondences file
void load_sound_correspondences(const gchar *filename);
void free_sound_correspondences();
#endif // COMPARE_H
Updated compare.c:
We've implemented the Union-Find data structure and adjusted the functions to handle multiple languages and words.
c
Updated main.c:
We've modified the GUI to be symmetrical and to allow inputting multiple languages and words. The GUI now supports up to four languages/words for comparison.
c
Makefile:
No changes are needed in the Makefile besides ensuring it references the new files.
makefile
CC = gcc
CFLAGS = `pkg-config --cflags gtk+-3.0 glib-2.0`
LIBS = `pkg-config --libs gtk+-3.0 glib-2.0`
all: main
main: main.c compare.c compare.h
$(CC) -o main main.c compare.c $(CFLAGS) $(LIBS)
clean:
rm -f main
Explanation of Changes:
CSV Parsing and Data Structures:
We updated the load_sound_correspondences function to read multiple sounds per line, grouping them as interchangeable.
Implemented a Union-Find data structure (UFNode) to manage these groups, allowing efficient queries about whether sounds belong to the same group.
Comparison Logic:
In find_sound_correspondences, we now accept multiple words and compare their sounds positionally.
We check if all sounds at a particular position across all words belong to the same group (i.e., correspond according to our expanded CSV file).
GUI Enhancements:
Modified the GUI in main.c to allow inputting up to four languages and words, making it more symmetrical.
Each language and its corresponding word are displayed in separate columns, and users can enter data in any of them.
Result Formatting:
The format_correspondences function now reports correspondences at each position, indicating whether the sounds at that position correspond across the entered languages.
With these changes, the program now supports:
Multiple Languages and Words:
Users can compare up to four words from different languages simultaneously.
Expanded Sound Correspondences:
The program considers a broader set of sound correspondences, thanks to the updated CSV file.
Dynamic Sound Correspondence Groups:
By using the Union-Find structure, we effectively group sounds that correspond, no matter how many sounds are in a group.
Note: To run this updated program, ensure that you have the GTK+3.0 and GLib 2.0 development libraries installed, and compile using the provided Makefile. Also, make sure that the sound_correspondences.csv file is in the same directory as the executable.
Dataset releases
Not yet included in a published release.
// compare.c
#include <stdio.h>
#include <string.h>
#include <glib.h>
#include "compare.h"
// Union-Find Node
typedef struct UFNode {
gchar *sound;
struct UFNode *parent;
} UFNode;
// Hash table mapping sounds to UFNodes
static GHashTable *sound_nodes = NULL;
// Find function for Union-Find
static UFNode* uf_find(UFNode *node) {
if (node->parent != node) {
node->parent = uf_find(node->parent);
}
return node->parent;
}
// Union function for Union-Find
static void uf_union(UFNode *node1, UFNode *node2) {
UFNode *root1 = uf_find(node1);
UFNode *root2 = uf_find(node2);
if (root1 != root2) {
root2->parent = root1;
}
}
// Create or get UFNode for a sound
static UFNode* get_or_create_ufnode(const gchar *sound) {
UFNode *node = g_hash_table_lookup(sound_nodes, sound);
if (!node) {
node = g_new(UFNode, 1);
node->sound = g_strdup(sound);
node->parent = node;
g_hash_table_insert(sound_nodes, node->sound, node);
}
return node;
}
// Load sound correspondences from file
void load_sound_correspondences(const gchar *filename) {
if (sound_nodes != NULL) {
// Free previous data
free_sound_correspondences();
}
sound_nodes = g_hash_table_new_full(g_str_hash, g_str_equal, NULL, NULL);
// Open file
FILE *file = fopen(filename, "r");
if (!file) {
g_warning("Failed to open correspondence file: %s", filename);
return;
}
char line[1024];
while (fgets(line, sizeof(line), file)) {
gchar **tokens = g_strsplit(line, ",", -1);
GPtrArray *nodes_in_line = g_ptr_array_new();
for (guint i = 0; tokens[i] != NULL; i++) {
gchar *sound = g_strstrip(tokens[i]);
if (g_strcmp0(sound, "") != 0) {
UFNode *node = get_or_create_ufnode(sound);
g_ptr_array_add(nodes_in_line, node);
}
}
// Union all nodes in this line
for (guint i = 1; i < nodes_in_line->len; i++) {
uf_union(g_ptr_array_index(nodes_in_line, 0), g_ptr_array_index(nodes_in_line, i));
}
g_ptr_array_free(nodes_in_line, TRUE);
g_strfreev(tokens);
}
fclose(file);
}
// Free sound correspondences data
void free_sound_correspondences() {
if (sound_nodes != NULL) {
GHashTableIter iter;
gpointer key, value;
g_hash_table_iter_init(&iter, sound_nodes);
while (g_hash_table_iter_next(&iter, &key, &value)) {
UFNode *node = (UFNode *)value;
g_free(node->sound);
g_free(node);
}
g_hash_table_destroy(sound_nodes);
sound_nodes = NULL;
}
}
// Split word into sounds
GArray* split_word_into_sounds(const gchar *word) {
GArray *sounds = g_array_new(FALSE, FALSE, sizeof(gchar *));
const gchar *p = word;
while (*p) {
gunichar c = g_utf8_get_char(p);
int char_len = g_unichar_to_utf8(c, NULL);
// Handle multi-character sounds if necessary
// For now, we assume each sound is one Unicode character
gchar *sound = g_utf8_substring(p, 0, 1);
g_array_append_val(sounds, sound);
p = g_utf8_next_char(p);
}
return sounds;
}
// Free sounds array
void free_sounds_array(GArray *sounds) {
for (guint i = 0; i < sounds->len; i++) {
gchar *sound = g_array_index(sounds, gchar *, i);
g_free(sound);
}
g_array_free(sounds, TRUE);
}
// Structure to hold correspondences at a position
typedef struct {
guint position;
GPtrArray *sounds; // Array of gchar* for each language at this position
} PositionCorrespondence;
// Find sound correspondences among multiple words
GArray* find_sound_correspondences(GPtrArray *words) {
GArray *sounds_arrays[words->len];
guint min_length = G_MAXUINT;
// Split each word into sounds
for (guint i = 0; i < words->len; i++) {
const gchar *word = (const gchar *)g_ptr_array_index(words, i);
GArray *sounds = split_word_into_sounds(word);
sounds_arrays[i] = sounds;
if (sounds->len < min_length) {
min_length = sounds->len;
}
}
GArray *result = g_array_new(FALSE, FALSE, sizeof(PositionCorrespondence));
// For each position
for (guint pos = 0; pos < min_length; pos++) {
GPtrArray *sounds_at_pos = g_ptr_array_new_with_free_func(g_free);
// Collect sounds at this position from all words
for (guint i = 0; i < words->len; i++) {
gchar *sound = g_array_index(sounds_arrays[i], gchar *, pos);
g_ptr_array_add(sounds_at_pos, g_strdup(sound));
}
// Add to result
PositionCorrespondence pc = { pos, sounds_at_pos };
g_array_append_val(result, pc);
}
// Free sounds arrays
for (guint i = 0; i < words->len; i++) {
free_sounds_array(sounds_arrays[i]);
}
return result;
}
// Format correspondences
gchar* format_correspondences(GArray *correspondences, GPtrArray *languages) {
GString *result = g_string_new("");
if (correspondences->len == 0) {
g_string_append(result, "No sound correspondences found.");
} else {
for (guint i = 0; i < correspondences->len; i++) {
PositionCorrespondence pc = g_array_index(correspondences, PositionCorrespondence, i);
// For each sound at this position, check if they correspond
gboolean all_correspond = TRUE;
UFNode *group = NULL;
GString *sounds_str = g_string_new("");
for (guint j = 0; j < pc.sounds->len; j++) {
gchar *sound = (gchar *)g_ptr_array_index(pc.sounds, j);
UFNode *node = g_hash_table_lookup(sound_nodes, sound);
if (!node) {
// The sound is not in the correspondences
all_correspond = FALSE;
} else {
UFNode *root = uf_find(node);
if (!group) {
group = root;
} else if (group != root) {
all_correspond = FALSE;
}
}
g_string_append_printf(sounds_str, "/%s/ (%s)", sound, (const gchar *)g_ptr_array_index(languages, j));
if (j < pc.sounds->len -1) {
g_string_append(sounds_str, ", ");
}
}
if (all_correspond) {
g_string_append_printf(result, "At position %u, sounds correspond: %s.\n", pc.position + 1, sounds_str->str);
} else {
g_string_append_printf(result, "At position %u, sounds do not correspond: %s.\n", pc.position + 1, sounds_str->str);
}
g_string_free(sounds_str, TRUE);
// Free sounds at position
g_ptr_array_free(pc.sounds, TRUE);
}
}
g_array_free(correspondences, TRUE);
gchar *final_result = result->str;
g_string_free(result, FALSE);
return final_result;
}
// main.c
#include <gtk/gtk.h>
#include "compare.h"
#define MAX_LANGUAGES 4
static void on_compare_button_clicked(GtkButton *button, gpointer user_data) {
GtkEntry **entries_word = g_object_get_data(G_OBJECT(button), "entries_word");
GtkEntry **entries_lang = g_object_get_data(G_OBJECT(button), "entries_lang");
GtkTextView *textview_results = GTK_TEXT_VIEW(g_object_get_data(G_OBJECT(button), "textview_results"));
GPtrArray *words = g_ptr_array_new_with_free_func(g_free);
GPtrArray *languages = g_ptr_array_new_with_free_func(g_free);
gboolean words_entered = FALSE;
for (guint i = 0; i < MAX_LANGUAGES; i++) {
const gchar *word = gtk_entry_get_text(entries_word[i]);
const gchar *lang = gtk_entry_get_text(entries_lang[i]);
if (g_strcmp0(word, "") != 0) {
words_entered = TRUE;
g_ptr_array_add(words, g_strdup(word));
g_ptr_array_add(languages, g_strdup(lang));
}
}
if (!words_entered) {
GtkWidget *dialog = gtk_message_dialog_new(NULL,
GTK_DIALOG_DESTROY_WITH_PARENT,
GTK_MESSAGE_ERROR,
GTK_BUTTONS_OK,
"Please enter at least one word for comparison.");
gtk_dialog_run(GTK_DIALOG(dialog));
gtk_widget_destroy(dialog);
return;
}
GArray *correspondences = find_sound_correspondences(words);
gchar *result_text = format_correspondences(correspondences, languages);
GtkTextBuffer *buffer = gtk_text_view_get_buffer(textview_results);
gtk_text_buffer_set_text(buffer, result_text, -1);
g_free(result_text);
g_ptr_array_free(words, TRUE);
g_ptr_array_free(languages, TRUE);
}
int main(int argc, char *argv[]) {
gtk_init(&argc, &argv);
// Load sound correspondences from file
load_sound_correspondences("sound_correspondences.csv");
GtkWidget *window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
gtk_window_set_title(GTK_WINDOW(window), "Word Comparison");
gtk_window_set_default_size(GTK_WINDOW(window), 800, 600);
g_signal_connect(window, "destroy", G_CALLBACK(gtk_main_quit), NULL);
GtkWidget *grid = gtk_grid_new();
gtk_container_add(GTK_CONTAINER(window), grid);
// Arrays to hold entries for languages and words
GtkEntry *entries_lang[MAX_LANGUAGES];
GtkEntry *entries_word[MAX_LANGUAGES];
// Create labels and entries for languages and words
for (guint i = 0; i < MAX_LANGUAGES; i++) {
gchar *label_lang_text = g_strdup_printf("Language %u:", i + 1);
GtkWidget *label_lang = gtk_label_new(label_lang_text);
g_free(label_lang_text);
entries_lang[i] = GTK_ENTRY(gtk_entry_new());
gchar *default_lang = g_strdup_printf("Language %u", i + 1);
gtk_entry_set_text(entries_lang[i], default_lang);
g_free(default_lang);
gchar *label_word_text = g_strdup_printf("Word %u:", i + 1);
GtkWidget *label_word = gtk_label_new(label_word_text);
g_free(label_word_text);
entries_word[i] = GTK_ENTRY(gtk_entry_new());
// Attach to grid
gtk_grid_attach(GTK_GRID(grid), label_lang, i, 0, 1, 1);
gtk_grid_attach(GTK_GRID(grid), GTK_WIDGET(entries_lang[i]), i, 1, 1, 1);
gtk_grid_attach(GTK_GRID(grid), label_word, i, 2, 1, 1);
gtk_grid_attach(GTK_GRID(grid), GTK_WIDGET(entries_word[i]), i, 3, 1, 1);
}
GtkWidget *button_compare = gtk_button_new_with_label("Compare");
// Text view for displaying results
GtkWidget *textview_results = gtk_text_view_new();
gtk_text_view_set_editable(GTK_TEXT_VIEW(textview_results), FALSE);
// Attach compare button and text view
gtk_grid_attach(GTK_GRID(grid), button_compare, 0, 4, MAX_LANGUAGES, 1);
gtk_grid_attach(GTK_GRID(grid), textview_results, 0, 5, MAX_LANGUAGES, 1);
// Pass entries to callback
g_object_set_data(G_OBJECT(button_compare), "entries_lang", entries_lang);
g_object_set_data(G_OBJECT(button_compare), "entries_word", entries_word);
g_object_set_data(G_OBJECT(button_compare), "textview_results", textview_results);
g_signal_connect(button_compare, "clicked", G_CALLBACK(on_compare_button_clicked), NULL);
gtk_widget_show_all(window);
gtk_main();
// Free memory
free_sound_correspondences();
return 0;
}