Microsoft MVP성태의 닷넷 이야기
.NET Framework: 1154. "Hanja Hangul Project v1.01 (파이썬)"의 C# 버전 [링크 복사], [링크+제목 복사],
조회: 14540
글쓴 사람
정성태 (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

비밀번호

댓글 작성자
 




... 76  77  78  79  80  81  82  83  84  [85]  86  87  88  89  90  ...
NoWriterDateCnt.TitleFile(s)
11811정성태2/11/201920819오류 유형: 510. 서버 운영체제에 NVIDIA GeForce Experience 실행 시 wlanapi.dll 누락 문제
11810정성태2/11/201918494.NET Framework: 808. .NET Profiler - GAC 모듈에서 GAC 비-등록 모듈을 참조하는 경우의 문제
11809정성태2/11/201920640.NET Framework: 807. ClrMD를 이용해 메모리 덤프 파일로부터 특정 인스턴스를 참조하고 있는 소유자 확인
11808정성태2/8/201921954디버깅 기술: 123. windbg - 닷넷 응용 프로그램의 메모리 누수 분석
11807정성태1/29/201919849Windows: 156. 가상 디스크의 용량을 복구 파티션으로 인해 늘리지 못하는 경우 [4]
11806정성태1/29/201919524디버깅 기술: 122. windbg - 덤프 파일로부터 PID와 환경 변수 등의 정보를 구하는 방법
11805정성태1/28/201921640.NET Framework: 806. C# - int []와 object []의 차이로 이해하는 제네릭의 필요성 [4]파일 다운로드1
11804정성태1/24/201919531Windows: 155. diskpart - remove letter 이후 재부팅 시 다시 드라이브 문자가 할당되는 경우
11803정성태1/10/201918377디버깅 기술: 121. windbg - 닷넷 Finalizer 스레드가 멈춰있는 현상
11802정성태1/7/201920110.NET Framework: 805. 두 개의 윈도우를 각각 실행하는 방법(Windows Forms, WPF)파일 다운로드1
11801정성태1/1/201921439개발 환경 구성: 427. Netsh의 네트워크 모니터링 기능 [3]
11800정성태12/28/201820509오류 유형: 509. WCF 호출 오류 메시지 - System.ServiceModel.CommunicationException: Internal Server Error
11799정성태12/19/201822234.NET Framework: 804. WPF(또는 WinForm)에서 UWP UI 구성 요소 사용하는 방법 [3]파일 다운로드1
11798정성태12/19/201821072개발 환경 구성: 426. vcpkg - "Building vcpkg.exe failed. Please ensure you have installed Visual Studio with the Desktop C++ workload and the Windows SDK for Desktop C++"
11797정성태12/19/201817082개발 환경 구성: 425. vcpkg - CMake Error: Problem with archive_write_header(): Can't create '' 빌드 오류
11796정성태12/19/201817317개발 환경 구성: 424. vcpkg - "File does not have expected hash" 오류를 무시하는 방법
11795정성태12/19/201820620Windows: 154. PowerShell - Zone 별로 DNS 레코드 유형 정보 조회 [1]
11794정성태12/16/201816718오류 유형: 508. Get-AzureWebsite : Request to a downlevel service failed.
11793정성태12/16/201819274개발 환경 구성: 423. NuGet 패키지 제작 - Native와 Managed DLL을 분리하는 방법 [1]
11792정성태12/11/201819079Graphics: 34. .NET으로 구현하는 OpenGL (11) - Per-Pixel Lighting파일 다운로드1
11791정성태12/11/201819083VS.NET IDE: 130. C/C++ 프로젝트의 시작 프로그램으로 .NET Core EXE를 지정하는 경우 닷넷 디버깅이 안 되는 문제 [1]
11790정성태12/11/201817589오류 유형: 507. Could not save daemon configuration to C:\ProgramData\Docker\config\daemon.json: Access to the path 'C:\ProgramData\Docker\config' is denied.
11789정성태12/10/201831180Windows: 153. C# - USB 장치의 연결 및 해제 알림을 위한 WM_DEVICECHANGE 메시지 처리 [2]파일 다운로드2
11788정성태12/4/201817457오류 유형: 506. SqlClient - Value was either too large or too small for an Int32.Couldn't store <2151292191> in ... Column
11787정성태11/29/201821596Graphics: 33. .NET으로 구현하는 OpenGL (9), (10) - OBJ File Format, Loading 3D Models파일 다운로드1
11786정성태11/29/201818584오류 유형: 505. OpenGL.NET 예제 실행 시 "Managed Debugging Assistant 'CallbackOnCollectedDelegate'" 예외 발생
... 76  77  78  79  80  81  82  83  84  [85]  86  87  88  89  90  ...