2017-05-12 7 views
0

나는 다양한 조건에 따라 자세한 텍스트 메시지를 만드는 C# 응용 프로그램을 가지고 있습니다. 하나 이상의 어커런스가있는 경우 메시지의 여러 단어로 된 복수형을 사용해야하며 모든 관련 부분이 정확하게 일치해야합니다. 그러한 언어의 위험성이 있지만, 이것을 처리 할 수있는 좋은 방법이 있는지 궁금합니다. 현재 내가 KLUGE 진짜 고통이며 다음과 같이 뭔가를 할복수 문구가있는 텍스트 문법

 "The letter corresponds properly.\n" + 
     "It must be capitalized.\n"; 

     "The letters correspond properly.\n" + 
     "They must be capitalized.\n"; 

: 아래의 첫 번째 세트는 하나 명의 발생을이고 두 번째는 하나 이상을위한 매우 간단한 예이며,

 string plural_s = plural ? "s" : ""; 
    string plural_s_negate = plural ? "" : "s"; 
    string plural_they = plural ? "They" : "It"; 

    "The letter" + plural_s + " correspond" + plural_s_negate + " properly.\n" + 
     plural_they + " must be capitalized.\n"; 

이 단순화 된 사례에서 문자 그대로 두 가지 사례를 모두 유지하고 선택하는 것이 더 낫겠지 만 많은 경우에 공통된 부분이 많은 설명이 길기 때문에 별도의 두 세트를 유지하고 싶지 않습니다. .

답변

2

Humanizer이 같은 작업을 수행하지만 사용자의 요구에 과도 함일 수 있으며 동시에 동사에 도움이되지 않습니다.

using System.Text.RegularExpressions; 
public static class PluralizeExtensions { 
    private static Dictionary<string, string> pluralForms = new Dictionary<string, string> { 
     { "letter", "letters" }, 
     { "corresponds", "correspond" }, 
     { "It", "They" } 
    }; 

    public static string Pluralize(this string text, bool isPlural) { 
     if (!isPlural) return text; 
     var words = Regex.Split(text, @"\b"); 
     for (int i = 0; i < words.Length; i++) { 
      if (pluralForms.ContainsKey(words[i])) words[i] = pluralForms[words[i]]; 
     } 
     return string.Join("", words); 
    } 
} 

당신은 다음과 같이 사용합니다 :

bool plural = WhateverYouDoToDecideIfItsPlural(); 

var text = ("The letter corresponds properly.\n" + 
      "It must be capitalized.\n").Pluralize(plural); 
당신이 조작 할 건지 말을 정확하게 알고있는 경우

, 당신은 사전 및 확장 방법을 사용하여 구문을 단순화 할 수 있습니다

유연성이 필요한 경우이 방법을 확장하여 대소 문자를보다 잘 처리 할 수 ​​있습니다.