Проверка латинской орфографии в R c пакетами hunspell и spelling
Загрузка словарей
Убедитесь, что у вас установлены нужные словари Hunspell.
- Linux and macOS: ~/.config/rstudio/dictionaries/languages-system/
- Windows: %AppData%\RStudio\dictionaries\languages-system\
Если латинский словарь не установлен, скачайте его по ссылке и добавьте файлы .dic и .aff в папку со словарями.
Поиск ошибок с hunspell
library(spelling) library(hunspell) library(stringr)
Убедимся, что словари Hunspell доступны и нормально работают.
# Dictionary customization
dict <- dictionary("la_LA")
# Basic spell checking with hunspell
ocr_text <- "Gallia est omnis divisa in partes tres, quarum unam incolnt Belgae, aliam Aquitani, tertiam qui ipsorum lingua Celtae, nostra Galli appelantur."
# Find misspelled words
misspelled <- hunspell(ocr_text, dict = dict)
misspelled
#[[1]]
#[1] "incolnt" "appelantur"Получим предложения по исправлению. Hunspell не учитывает контекст и просто ищет ближайшие строки.
Так не получится найти ошибку, если использована неправильная, но возможная форма слова, например omne вместо omnis.
# Get suggestions for corrections suggestions <- hunspell_suggest(unlist(misspelled), dict = dict) suggestions #[[1]] ##[1] "incolt" "incolant" "incolent" "incolunt" "incolvnt" "incolit" "incolat" ##[8] "incolet" "incolut" "incolvt" "incolo" #[[2]] ##[1] "appellantur" "appetantur"
Если вы хотите добавить пользовательские слова в словарь (например, имена собственные), это можно сделать так:
dict <- hunspell::dictionary("la_LA", add_words = my_word_vec)Исправление
Автоматическая замена ошибки не рекомендуется, т.к. hunspell может предлагать несколько вариантов, и не всегда первый из них будет подходящим.
Код ниже позволит пользователю пройтись по всем исправлениям и выбрать нужный вариант (или пропустить слово) вручную в интерактивном режиме.
На этот раз текст для проверки хранится в файле text_lat.txt.
# Read the text file
text_lines <- readLines("text_lat.txt", encoding = "UTF-8", warn = FALSE)
# Get misspelled words
# Use ignore argument to skip custom words
errors <- spell_check_files("text_lat.txt", lang = "la_LA")
# For each error, get suggestions and prompt user
for (i in 1:nrow(errors)) {
word <- errors$word[i]
line_num <- str_replace(errors$found[i], ".*:(\\d+)", "\\1") |>
as.numeric()
# Extract the line containing the error
original_line <- text_lines[line_num]
# Get Hunspell suggestions
suggestions <- hunspell_suggest(word, dict = dictionary("la_LA"))[[1]]
# Add "Skip", "Quit", and manual entry options
options <- c(suggestions, "Skip", "Quit correction process", "Enter manually...")
# Show the context
cat("\nMisspelled word in context:\n")
cat(str_view(original_line, word))
# Prompt user
choice <- menu(
options,
title = "\nChoose a replacement (0 to skip):"
)
if (choice == 0 || options[choice] == "Skip") {
next
} else if (options[choice] == "Quit correction process") {
cat("\nQuitting correction process. Saving current progress...\n")
break # Exit the for loop
} else if (options[choice] == "Enter manually...") {
replacement <- readline("Enter correction: ")
} else {
replacement <- options[choice]
}
# Replace the word in the line
text_lines[line_num] <- gsub(
paste0("\\b", word, "\\b"),
replacement,
text_lines[line_num]
)
writeLines(text_lines, "corrected_text.txt", useBytes = TRUE)
cat("\nCorrected text saved to 'corrected_text.txt'\n")
}
Запуск кода позволит вносить исправления прямо в консоли:
Предложенное решение может использоваться для "очистки" текста после OCR.