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

비밀번호

댓글 작성자
 




... [91]  92  93  94  95  96  97  98  99  100  101  102  103  104  105  ...
NoWriterDateCnt.TitleFile(s)
11660정성태8/19/201818633사물인터넷: 33. 세라믹 커패시터의 동작 방식파일 다운로드1
11659정성태8/19/201818481사물인터넷: 32. 9V 전압에서 테스트하는 PN2222A 트랜지스터파일 다운로드1
11658정성태8/18/201821957사물인터넷: 31. 커패시터와 RC 회로파일 다운로드3
11657정성태8/18/201819961사물인터넷: 30. 릴레이(Relay) 제어파일 다운로드3
11656정성태8/16/201815721사물인터넷: 29. 트랜지스터와 병렬로 연결한 LED파일 다운로드1
11655정성태8/16/201817971사물인터넷: 28. 저항과 병렬로 연결한 LED파일 다운로드1
11654정성태8/15/201819237사물인터넷: 27. 병렬 회로의 저항, 전압 및 전류파일 다운로드1
11653정성태8/14/201820076사물인터넷: 26. 입력 전압에 따른 LED의 전압/저항 변화 [1]파일 다운로드1
11652정성태8/14/201817504사물인터넷: 25. 컬렉터 9V, 베이스에 5V와 3.3V 전압으로 테스트하는 C1815 트랜지스터파일 다운로드1
11651정성태8/14/201822632사물인터넷: 24. 9V 전압에서 테스트하는 C1815 트랜지스터 [1]파일 다운로드3
11650정성태8/14/201817040사물인터넷: 23. 가변저항으로 분압파일 다운로드1
11649정성태8/12/201819375사물인터넷: 22. 저항에 따른 전류 테스트파일 다운로드1
11648정성태8/12/201820790사물인터넷: 21. 퓨즈를 이용한 회로 보호파일 다운로드3
11647정성태8/8/201820934오류 유형: 476. 음수의 음수는 여전히 음수가 되는 수(절대값이 음수인 수)
11646정성태8/8/201816950오류 유형: 475. gacutil.exe 실행 시 "Failure initializing gacutil" 오류 발생
11645정성태8/8/201819169오류 유형: 474. 닷넷 COM+ - Failed to load the runtime. [1]
11644정성태8/6/201822061디버깅 기술: 118. windbg - 닷넷 개발자를 위한 MEX Debugging Extension 소개
11643정성태8/6/201821679사물인터넷: 20. 아두이노 레오나르도 R3 호환 보드의 3.3v 핀의 LED 전압/전류 테스트 [1]파일 다운로드1
11642정성태8/3/201820485Graphics: 20. Unity - LightMode의 ForwardBase에 따른 _WorldSpaceLightPos0 값 변화
11641정성태8/3/201826000Graphics: 19. Unity로 실습하는 Shader (10) - 빌보드 구현 [1]파일 다운로드1
11640정성태8/3/201822191Graphics: 18. Unity - World matrix(unity_ObjectToWorld)로부터 Position, Rotation, Scale 값을 복원하는 방법파일 다운로드1
11639정성태8/2/201819755디버깅 기술: 117. windbg - 덤프 파일로부터 추출한 DLL을 참조하는 방법
11638정성태8/2/201818148오류 유형: 473. windbg - 덤프 파일로부터 추출한 DLL 참조 시 "Resolved file has a bad image, no metadata, or is otherwise inaccessible." 빌드 오류
11637정성태8/1/201822556Graphics: 17. Unity - World matrix(unity_ObjectToWorld)로부터 TRS(이동/회전/크기) 행렬로 복원하는 방법파일 다운로드1
11636정성태8/1/201829966Graphics: 16. 3D 공간에서 두 점이 이루는 각도 구하기파일 다운로드1
11635정성태8/1/201818677오류 유형: 472. C# 컴파일 오류 - Your project is not referencing the ".NETFramework,Version=v3.5" framework.
... [91]  92  93  94  95  96  97  98  99  100  101  102  103  104  105  ...