簡體   English   中英

替換 C# 中的字符 (ascii)

[英]Replacing characters in C# (ascii)

我得到了一個包含以下字符的文件:à、è、ì、ò、ù - À。 我需要做的是用普通字符替換這些字符,例如:à = a, è = e 等等.....這是我目前的代碼:

StreamWriter sw = new StreamWriter(@"C:/JoinerOutput.csv");
string path = @"C:/Joiner.csv";
string line = File.ReadAllText(path);

if (line.Contains("à"))
{
    string asAscii = Encoding.ASCII.GetString(Encoding.Convert(Encoding.UTF8, Encoding.GetEncoding(Encoding.ASCII.EncodingName, new EncoderReplacementFallback("a"), new DecoderExceptionFallback()), Encoding.UTF8.GetBytes(line)));
    Console.WriteLine(asAscii);
    Console.ReadLine();

    sw.WriteLine(asAscii);
    sw.Flush();
}

基本上這會在文件中搜索特定字符並將其替換為另一個字符。 我遇到的問題是我的 if 語句不起作用。 我該如何解決這個問題?

這是輸入文件的示例:

Dimàkàtso Mokgàlo
Màmà Ràtlàdi
Koos Nèl
Pàsèkà Modisè
Jèrèmiàh Morèmi
Khèthiwè Buthèlèzi
Tiànà Pillày
Viviàn Màswàngànyè
Thirèshàn Rèddy
Wàdè Cornèlius
ènos Nètshimbupfè

這是如果使用的輸出: line = line.Replace('à', 'a');

Ch�rl�n� Kirst�n
M�m� R�tl�di
Koos N�l
P�s�k� Modis�
J�r�mi�h Mor�mi
Kh�thiw� Buth�l�zi
Ti�n� Pill�y
Vivi�n M�sw�ng�ny�
Thir�sh�n R�ddy
W�d� Corn�lius
�nos N�tshimbupf�

使用我的代碼,符號將被完全刪除

其他人評論了使用 Unicode 查找表來刪除變音符號。 我做了一個快速的谷歌搜索,找到了這個例子 代碼無恥地復制,(重新格式化),並貼在下面:

using System;
using System.Text;
using System.Globalization;

public static class Remove
{
    public static string RemoveDiacritics(string stIn)
    {
        string stFormD = stIn.Normalize(NormalizationForm.FormD);
        StringBuilder sb = new StringBuilder();

        for(int ich = 0; ich < stFormD.Length; ich++) {
            UnicodeCategory uc = CharUnicodeInfo.GetUnicodeCategory(stFormD[ich]);
            if(uc != UnicodeCategory.NonSpacingMark) {
                sb.Append(stFormD[ich]);
            }
        }

        return(sb.ToString().Normalize(NormalizationForm.FormC));
    }
}

因此,您的代碼可以通過調用來清理輸入:

line = Remove.RemoveDiacritics(line);

不知道它是否有用,但在一個在 LED 屏幕上寫消息的內部工具中,我們有以下替換(我確信有更智能的方法可以使 unicode 表工作,但這一個就足夠了對於這個小型內部工具):

        strMessage = Regex.Replace(strMessage, "[éèëêð]", "e");
        strMessage = Regex.Replace(strMessage, "[ÉÈËÊ]", "E");
        strMessage = Regex.Replace(strMessage, "[àâä]", "a");
        strMessage = Regex.Replace(strMessage, "[ÀÁÂÃÄÅ]", "A");
        strMessage = Regex.Replace(strMessage, "[àáâãäå]", "a");
        strMessage = Regex.Replace(strMessage, "[ÙÚÛÜ]", "U");
        strMessage = Regex.Replace(strMessage, "[ùúûüµ]", "u");
        strMessage = Regex.Replace(strMessage, "[òóôõöø]", "o");
        strMessage = Regex.Replace(strMessage, "[ÒÓÔÕÖØ]", "O");
        strMessage = Regex.Replace(strMessage, "[ìíîï]", "i");
        strMessage = Regex.Replace(strMessage, "[ÌÍÎÏ]", "I");
        strMessage = Regex.Replace(strMessage, "[š]", "s");
        strMessage = Regex.Replace(strMessage, "[Š]", "S");
        strMessage = Regex.Replace(strMessage, "[ñ]", "n");
        strMessage = Regex.Replace(strMessage, "[Ñ]", "N");
        strMessage = Regex.Replace(strMessage, "[ç]", "c");
        strMessage = Regex.Replace(strMessage, "[Ç]", "C");
        strMessage = Regex.Replace(strMessage, "[ÿ]", "y");
        strMessage = Regex.Replace(strMessage, "[Ÿ]", "Y");
        strMessage = Regex.Replace(strMessage, "[ž]", "z");
        strMessage = Regex.Replace(strMessage, "[Ž]", "Z");
        strMessage = Regex.Replace(strMessage, "[Ð]", "D");
        strMessage = Regex.Replace(strMessage, "[œ]", "oe");
        strMessage = Regex.Replace(strMessage, "[Œ]", "Oe");
        strMessage = Regex.Replace(strMessage, "[«»\u201C\u201D\u201E\u201F\u2033\u2036]", "\"");
        strMessage = Regex.Replace(strMessage, "[\u2026]", "...");

需要注意的一件事是,如果在大多數語言中,經過這種處理后文本仍然可以理解,情況並非總是如此,並且通常會迫使讀者參考句子的上下文才能理解它。 如果你有選擇,這不是你想要的。


請注意,正確的解決方案是使用 unicode 表,用“組合變音符號”+字符形式替換帶有集成變音符號的字符,然后刪除變音符號......

我經常使用基於 Dana 提供的版本的擴展方法。 快速解釋:

  • 規范化形成 D 將è 等字符拆分為e和非間距`
  • 從此,刪除了 nospacing 字符
  • 結果被歸一化回形式 D(我不確定這是否必要)

代碼:

using System.Linq;
using System.Text;
using System.Globalization;

// namespace here
public static class Utility
{
    public static string RemoveDiacritics(this string str)
    {
        if (str == null) return null;
        var chars =
            from c in str.Normalize(NormalizationForm.FormD).ToCharArray()
            let uc = CharUnicodeInfo.GetUnicodeCategory(c)
            where uc != UnicodeCategory.NonSpacingMark
            select c;

        var cleanStr = new string(chars.ToArray()).Normalize(NormalizationForm.FormC);

        return cleanStr;
    }
}

你為什么要把事情復雜化?

line = line.Replace('à', 'a');

更新:

File.ReadAllText的文檔說:

此方法嘗試根據字節順序標記的存在自動檢測文件的編碼。 可以檢測編碼格式 UTF-8 和 UTF-32(大端和小端)。

讀取可能包含導入文本的文件時,請使用 ReadAllText(String, Encoding) 方法重載,因為可能無法正確讀取無法識別的字符。

C:/Joiner.csv是什么編碼? 也許您應該為File.ReadAllText使用其他重載,您可以在其中自己指定輸入編碼?

用簡單的方法做。 下面的代碼將僅用 2 行代碼將所有特殊字符替換為 ASCII 字符。 它為您提供與 Julien Roncaglia 的解決方案相同的結果。

byte[] bytes = System.Text.Encoding.GetEncoding("Cyrillic").GetBytes(inputText);
string outputText = System.Text.Encoding.ASCII.GetString(bytes);

用這個:

     if (line.Contains(“OldChar”))
     {
        line = line.Replace(“OldChar”, “NewChar”);
     }

聽起來您想要做的是將擴展 ASCII(八位)轉換為 ASCII(七位)-因此搜索可能會有所幫助。

我見過用其他語言處理這個的庫,但從來沒有在 C# 中這樣做過,但這看起來可能有點啟發:

將兩個 ascii 字符轉換為它們的“對應”一個字符擴展 ascii 表示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM