Microsoft MVP성태의 닷넷 이야기
.NET Framework: 1154. "Hanja Hangul Project v1.01 (파이썬)"의 C# 버전 [링크 복사], [링크+제목 복사],
조회: 14510
글쓴 사람
정성태 (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)
11685정성태9/6/201818474사물인터넷: 40. 이어폰 소리를 capacitor로 필터링파일 다운로드1
11684정성태9/6/201821101개발 환경 구성: 396. pagefile.sys를 비활성화시켰는데도 working set 메모리가 줄어드는 이유파일 다운로드1
11683정성태9/5/201818722개발 환경 구성: 395. Azure Web App의 이벤트 로그를 확인하는 방법
11682정성태9/5/201817671오류 유형: 484. Fakes를 포함한 단위 테스트 프로젝트를 빌드 시 CS1729 관련 오류 발생
11681정성태9/5/201820373Windows: 149. 다른 컴퓨터의 윈도우 이벤트 로그를 구독하는 방법 [2]
11680정성태9/2/201822545Graphics: 21. shader - _Time 내장 변수를 이용한 UV 변동 효과파일 다운로드1
11679정성태8/30/201820544.NET Framework: 792. C# COM 서버가 제공하는 COM 이벤트를 C++에서 받는 방법 [1]파일 다운로드1
11678정성태8/29/201818974오류 유형: 483. 닷넷 - System.InvalidProgramException [1]
11677정성태8/29/201816728오류 유형: 482. TFS - Could not find a part of the path '...\packages\Microsoft.AspNet.WebApi.5.2.5\.signature.p7s'.
11676정성태8/29/201827570.NET Framework: 791. C# - ElasticSearch를 위한 Client 라이브러리 제작 [1]파일 다운로드1
11675정성태8/29/201817751오류 유형: 481. The located assembly's manifest definition does not match the assembly reference.
11674정성태8/29/201819722Phone: 12. Xamarin - 기존 리모컨 기능을 핸드폰의 적외선 송신으로 구현파일 다운로드1
11673정성태8/28/201816990오류 유형: 480. Fritzing 실행 시 Ordinal Not Found 오류
11672정성태8/28/201817428오류 유형: 479. 윈도우 - 시스템 설정에서 도메인 참가를 위한 "Change" 버튼이 비활성화된 경우
11671정성태8/28/201823819사물인터넷: 39. 아두이노에서 적외선 송신기 기본 사용법파일 다운로드1
11670정성태8/28/201822050사물인터넷: 38. 아두이노에서 적외선 수신기 기본 사용법 [1]파일 다운로드1
11669정성태8/24/201820829개발 환경 구성: 394. 윈도우 환경에서 elasticsearch의 한글 블로그 검색 인덱스 구성
11668정성태8/24/201831849오류 유형: 478. 윈도우 업데이트(KB4458842) 이후 SQL Server 서비스 시작 오류
11667정성태8/24/201818635오류 유형: 477. "Use Unicode UTF-8 for worldwide language support" 옵션 설정 시 SQL Server 2016 설치 오류 [1]
11666정성태8/22/201818543사물인터넷: 37. 아두이노 - 코딩으로 대신하는 오실레이터 회로의 소리 출력파일 다운로드1
11665정성태8/22/201821233사물인터넷: 36. 오실레이터 회로 동작을 아두이노의 코딩으로 구현하는 방법파일 다운로드1
11664정성태8/22/201820860개발 환경 구성: 393. 윈도우 환경에서 elasticsearch의 한글 형태소 분석기 설치 [1]
11663정성태8/22/201823578개발 환경 구성: 392. 윈도우 환경에서 curl.exe를 이용한 elasticsearch 6.x 기본 사용법
11662정성태8/21/201817245사물인터넷: 35. 병렬 회로에서의 커패시터파일 다운로드1
11661정성태8/21/201819555사물인터넷: 34. 트랜지스터 동작 - 컬렉터-이미터 간의 저항 측정파일 다운로드1
11660정성태8/19/201818633사물인터넷: 33. 세라믹 커패시터의 동작 방식파일 다운로드1
... 76  77  78  79  80  81  82  83  84  85  86  87  88  89  [90]  ...