Microsoft MVP성태의 닷넷 이야기
.NET Framework: 1154. "Hanja Hangul Project v1.01 (파이썬)"의 C# 버전 [링크 복사], [링크+제목 복사]
조회: 6764
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 

"Hanja Hangul Project v1.01 (파이썬)"의 C# 버전"

아래와 같은 프로젝트가 있군요. ^^

Hanja Hangul Project v1.01 (파이썬)
; https://blog.daum.net/masoris20/187
; https://blog.daum.net/masoris20/186

재미있어서 C#으로도 포팅해봤습니다.

파이썬 코드를 포팅하는데 결정적인 요소는 "unicodedata.name(i)"의 기능을 구현하는 것입니다. 사실 꼭 그것과 동일하게 구현할 필요는 없지만, 어쨌든 유니코드 문자에 대한 코드 포인트 이름을 알려주는 것은 기존 BCL 라이브러리에는 없기 때문에 흥미롭습니다.

검색해 보면, 다행히 이에 대한 프로젝트가 이미 있어서 굳이 만들 필요는 없습니다.

UnicodeInformation
; https://www.nuget.org/packages/UnicodeInformation/

GoldenCrystal/NetUnicodeInfo
; https://github.com/GoldenCrystal/NetUnicodeInfo

따라서 이 패키지를 참조 추가해,

// Install-Package UnicodeInformation -Version 2.6.0

Install-Package UnicodeInformation

유니코드 문자에 대해 다음과 같은 결과를 얻을 수 있습니다.

Console.WriteLine(UnicodeInfo.GetName('蠶')); // CJK IDEOGRAPH-8836
Console.WriteLine(UnicodeInfo.GetName('가')); // HANGUL SYLLABLE GA
Console.WriteLine(UnicodeInfo.GetName('ㄱ')); // HANGUL LETTER KIYEOK

위의 메서드가 파이썬의 "unicodedata.name(i)" 함수와 동일한 결과를 반환하기 때문에 이제 남은 작업은 단순히 소스코드 변환만 하면 됩니다.

using System.Diagnostics;
using System.Text;
using System.Unicode;

namespace HanConv
{
    public static class Hanja2Hangul
    {
        public static List<string> MakeSplittedHanjaList(this string str)
        {
            List<string> list = new List<string>();

            if (string.IsNullOrEmpty(str))
            {
                return list;
            }

            str = str.Normalize(NormalizationForm.FormC);

            bool previous = str[0].IsHanja();
            List<char> word = new List<char>();

            word.Add(str[0]);

            foreach (char ch in str[1..])
            {
                bool current = ch.IsHanja();

                if (current != previous)
                {
                    list.Add(new string(word.ToArray()));
                    word.Clear();
                }

                word.Add(ch);
                previous = current;
            }

            if (word.Count > 0)
            {
                list.Add(new string(word.ToArray()));
            }

            return list;
        }

        public static string HanjaToHangulDueum(this string str)
        {
            str = str.Normalize(NormalizationForm.FormC);

            List<string> splitted = MakeSplittedHanjaList(str);
            StringBuilder sb = new StringBuilder();

            foreach (string word in splitted)
            {
                if (word.IsHanja())
                {
                    sb.Append(MakeDueum(HanjaToHangulSimple(word)));
                }
                else
                {
                    sb.Append(word);
                }
            }

            return sb.ToString();
        }

        private static string MakeDueum(string str)
        {
            if (string.IsNullOrEmpty(str))
            {
                return "";
            }

            char[] chArray = str.ToArray();
            chArray[0] = make_dueum_a_char(chArray[0]);
            if (chArray.Length == 1)
            {
                return $"{chArray[0]}";
            }

            char previous = chArray[0];
            for (int i = 1; i < chArray.Length; i++)
            {
                char ch = chArray[i];

                if (ch == '렬' && is_vowel_or_nieun(previous))
                {
                    chArray[i] = '열';
                }
                else if (ch == '률' && is_vowel_or_nieun(previous))
                {
                    chArray[i] = '율';
                }

                previous = ch;
            }

            return new string(chArray);
        }

        private static bool is_vowel_or_nieun(char ch)
        {
            if (ch.IsHangul() == false)
            {
                return false;
            }

            int n = ((int)ch - 0xAC00) % 28;
            if (n == 0 || n == 4)
            {
                return true;
            }

            return false;
        }

        private static char make_dueum_a_char(char ch)
        {
            if (ch.IsHangul() == false)
            {
                return ch;
            }

            if (HanConv.HanDict.Dueum.ContainsKey(ch))
            {
                return HanConv.HanDict.Dueum[ch];
            }

            return ch;
        }

        private static string HanjaToHangulSimple(string str)
        {
            char[] chArray = new char[str.Length];

            for (int i = 0; i < chArray.Length; i ++)
            {
                chArray[i] = HanConv.HanDict.Hanja[str[i]];
            }

            return new string(chArray);
        }

        public static bool IsHangul(this char ch)
        {
            return UnicodeInfo.GetName(ch).IndexOf("HANGUL") != -1;
        }

        public static bool IsHangul(this string str)
        {
            if (string.IsNullOrEmpty(str))
            {
                return false;
            }

            return str.Length == len_hangul(str);
        }

        private static int len_hangul(string str)
        {
            int count = 0;

            foreach (char c in str)
            {
                if (c.IsHangul())
                {
                    count++;
                }
            }

            return count;
        }

        public static bool IsHanja(this char ch)
        {
            return UnicodeInfo.GetName(ch) switch
            {
                String txt when txt.Length >= 3 && txt[0..3] == "CJK" => true,
                String txt when txt.Length >= 6 && txt[0..6] == "KANGXI" => true,
                _ => false,
            };
        }

        public static bool IsHanja(this string str)
        {
            if (string.IsNullOrEmpty(str))
            {
                return false;
            }

            return str.Length == len_hanja(str);
        }

        private static int len_hanja(string str)
        {
            int count = 0;

            foreach (char c in str)
            {
                if (c.IsHanja())
                {
                    count++;
                }
            }

            return count;
        }
    }
}

그런데, 실제로 위의 코드를 수행해 보면 처음 한 번의 GetName 호출에서 약간의 멈춤 현상이 발생합니다. 최초 한 번의 호출에서만 참으면 되는 건데, 이게 좀... 은근히 신경 쓰입니다. ^^; 이것의 원인은 UnicodeInformation 프로젝트가 내부에서 유니코드 정보를 가지고 있는 파일인 "ucd.dat"를 압축해서 보관했다가, 최초 GetName 호출에서 압축을 해제하느라 시간이 걸리기 때문입니다.

public static UnicodeData ReadFromResources()
{
    using (var stream = new DeflateStream(typeof(UnicodeData).GetTypeInfo().Assembly.GetManifestResourceStream("ucd.dat"), CompressionMode.Decompress, false))
    {
        return ReadFromStream(stream);
    }
}

Ucd.dat 파일은 압축 해제 시 3MB가 넘는 파일인데, 사실 근래의 스토리지/네트워크 환경에서 그다지 신경 쓰이는 크기는 아닙니다. 따라서, 그냥 저 파일을 압축하지 않고 저장하고 읽으면 되는데요, 재미있는 것은, UnicodeInformation 프로젝트가 저 파일을 수작업으로 생성하지 않고 빌드 프로세스에서 자동으로 생성/압축한다는 점입니다.

그래서, 단순히 저 파일을 압축만 해제해서 저장한다고 해도 다음번 빌드에서 다시 압축이 되기 때문에 그런 식으로 수정하면 안 되고, 근본적으로 System.Unicode.Build.Core 프로젝트의 UnicodeDatabaseGenerator.cs 파일의 코드를 (압축하지 않도록) 수정해야 합니다.

public static async ValueTask GenerateDatabase(HttpClient httpClient, string baseDirectory, string outputFilePath, bool? shouldDownloadFiles, bool? shouldSaveFiles, bool? shouldExtractFiles)
{
	UnicodeInfoBuilder data;

	baseDirectory = string.IsNullOrWhiteSpace(baseDirectory) ?
		Environment.CurrentDirectory :
		Path.GetFullPath(baseDirectory);

	using (var ucdSource = await GetDataSourceAsync(httpClient, UnicodeCharacterDataUri, baseDirectory, UcdDataSourceName, UcdRequiredFiles, true, shouldDownloadFiles, shouldSaveFiles, shouldExtractFiles))
	using (var unihanSource = await GetDataSourceAsync(httpClient, UnicodeCharacterDataUri, baseDirectory, UnihanDataSourceName, UnihanRequiredFiles, true, shouldDownloadFiles, shouldSaveFiles, shouldExtractFiles))
	using (var ucdEmojiSource = await GetDataSourceAsync(httpClient, UcdEmojiDataUri, baseDirectory, EmojiDataSourceName, UcdEmojiRequiredFiles, false, shouldDownloadFiles, shouldSaveFiles, shouldExtractFiles))
	//using (var emojiSource = await GetDataSourceAsync(httpClient, EmojiDataUri, baseDirectory, EmojiDataSourceName, EmojiRequiredFiles, false, shouldDownloadFiles, shouldSaveFiles, shouldExtractFiles))
	{
		data = await UnicodeDataProcessor.BuildDataAsync(ucdSource, unihanSource, ucdEmojiSource);
	}

	// This part is actually highly susceptible to framework version. Different frameworks give a different results.
	// In order to consistently produce the same result, the framework executing this code must be fixed.
	using (var stream = File.Create(outputFilePath))
		data.WriteToStream(stream);
}

이와 함께, System.Unicode.Build.Tasks 프로젝트의 GetUnicodeDatabaseVersion.cs 파일의 코드에서 압축 해제 코드도 없애고,

protected override async Task<bool> ExecuteAsync(CancellationToken cancellationToken)
{
	var buffer = new byte[8];

	using (var file = File.OpenRead(DatabasePath))
	{
		await file.ReadAsync(buffer, 0, buffer.Length);
	}

	if (TryReadHeader(buffer, out var version))
	{
		UnicodeDatabaseVersion = version.ToString(3);
		return true;
	}

	Log.LogError("The database contained an invalid header.");

	return false;
}

끝으로 System.Unicode 프로젝트의 UnicodeData.cs 파일에서 리소스에 대한 압축 해제 코드를 없애면 됩니다.

public static UnicodeData ReadFromResources()
{
    using (var stream = typeof(UnicodeData).GetTypeInfo().Assembly.GetManifestResourceStream("ucd.dat"))
    {
        return ReadFromStream(stream);
    }
}

이후 아주 빠르게 GetName 메서드가 수행되는 것을 확인할 수 있습니다.




현재 위와 같이 변경한 UnicodeInformation 어셈블리를 참조하는 패키지(nuget)와 소스코드(github)를 올려 두었습니다.

HanConv
; https://www.nuget.org/packages/HanConv/
; https://github.com/stjeong/HanjaHangul

// Install-Package HanConv -Version 1.0.1

Install-Package HanConv

따라서 이를 참조하고 실행하면 다음과 같은 결과를 얻을 수 있습니다.

using HanConv;

string text = "蠶段陽物是乎等用良水氣乙厭却桑葉叱分喫破爲遣飮水不冬";
Console.WriteLine(text.HanjaToHangulDueum()); // 잠단양물시호등용량수기을염각상엽질분끽파위견음수불동

단지 아쉬운 것은 두음법칙에 대한 처리가 완벽하지 않습니다. 가령 다음과 같은 테스트는 통과하지만,

[DataRow("羅列", "나열")]
[DataRow("雲量", "운량")]
[DataRow("羅州", "나주")]
[DataRow("靈巖", "영암")]
[DataRow("男女", "남녀")]
[DataRow("讀者欄", "독자란")]
[DataRow("隱匿", "은닉")]
[DataRow("李成桂", "이성계")]
public void HanjaToHangulDueumTest(string input, string expected)
{
    Assert.AreEqual(input.HanjaToHangulDueum(), expected);
}

아래와 같이 중간에 들어가는 두음법칙 단어는 처리하지 않고 있습니다.

[TestMethod()]
[DataRow("新女性", "신여성", "신녀성")]
[DataRow("國際聯合", "국제연합", "국제련합")]
[DataRow("空念佛", "공염불", "공념불")]
[DataRow("會計年度", "회계연도", "회계년도")]
[DataRow("許蘭雪軒", "허난설헌", "허란설헌")]
[DataRow("失樂園", "실낙원", "실락원")]
[DataRow("銃榴彈", "총유탄", "총류탄")]
public void HanjaToHangulDueumTest_ToImprove(string input, string myExpected, string result)
{
    Assert.AreEqual(input.HanjaToHangulDueum(), result);
    Assert.AreNotEqual(input.HanjaToHangulDueum(), myExpected);
}




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]







[최초 등록일: ]
[최종 수정일: 2/13/2022]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13602정성태4/20/2024223닷넷: 2244. C# - PCM 오디오 데이터를 연속(Streaming) 재생 (Windows Multimedia)파일 다운로드1
13601정성태4/19/2024264닷넷: 2243. C# - PCM 사운드 재생(NAudio)파일 다운로드1
13600정성태4/18/2024301닷넷: 2242. C# - 관리 스레드와 비관리 스레드
13599정성태4/17/2024472닷넷: 2241. C# - WAV 파일의 PCM 사운드 재생(Windows Multimedia)파일 다운로드1
13598정성태4/16/2024447닷넷: 2240. C# - WAV 파일 포맷 + LIST 헤더파일 다운로드2
13597정성태4/15/2024520닷넷: 2239. C# - WAV 파일의 PCM 데이터 생성 및 출력파일 다운로드1
13596정성태4/14/2024876닷넷: 2238. C# - WAV 기본 파일 포맷파일 다운로드1
13595정성태4/13/2024996닷넷: 2237. C# - Audio 장치 열기 (Windows Multimedia, NAudio)파일 다운로드1
13594정성태4/12/20241034닷넷: 2236. C# - Audio 장치 열람 (Windows Multimedia, NAudio)파일 다운로드1
13593정성태4/8/20241053닷넷: 2235. MSBuild - AccelerateBuildsInVisualStudio 옵션
13592정성태4/2/20241211C/C++: 165. CLion으로 만든 Rust Win32 DLL을 C#과 연동
13591정성태4/2/20241169닷넷: 2234. C# - WPF 응용 프로그램에 Blazor App 통합파일 다운로드1
13590정성태3/31/20241074Linux: 70. Python - uwsgi 응용 프로그램이 k8s 환경에서 OOM 발생하는 문제
13589정성태3/29/20241143닷넷: 2233. C# - 프로세스 CPU 사용량을 나타내는 성능 카운터와 Win32 API파일 다운로드1
13588정성태3/28/20241198닷넷: 2232. C# - Unity + 닷넷 App(WinForms/WPF) 간의 Named Pipe 통신파일 다운로드1
13587정성태3/27/20241157오류 유형: 900. Windows Update 오류 - 8024402C, 80070643
13586정성태3/27/20241305Windows: 263. Windows - 복구 파티션(Recovery Partition) 용량을 늘리는 방법
13585정성태3/26/20241096Windows: 262. PerformanceCounter의 InstanceName에 pid를 추가한 "Process V2"
13584정성태3/26/20241051개발 환경 구성: 708. Unity3D - C# Windows Forms / WPF Application에 통합하는 방법파일 다운로드1
13583정성태3/25/20241158Windows: 261. CPU Utilization이 100% 넘는 경우를 성능 카운터로 확인하는 방법
13582정성태3/19/20241423Windows: 260. CPU 사용률을 나타내는 2가지 수치 - 사용량(Usage)과 활용률(Utilization)파일 다운로드1
13581정성태3/18/20241591개발 환경 구성: 707. 빌드한 Unity3D 프로그램을 C++ Windows Application에 통합하는 방법
13580정성태3/15/20241138닷넷: 2231. C# - ReceiveTimeout, SendTimeout이 적용되지 않는 Socket await 비동기 호출파일 다운로드1
13579정성태3/13/20241494오류 유형: 899. HTTP Error 500.32 - ANCM Failed to Load dll
13578정성태3/11/20241631닷넷: 2230. C# - 덮어쓰기 가능한 환형 큐 (Circular queue)파일 다운로드1
[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...