2014-01-08 138 views
0

我有一个程序,做一些法语网页的屏幕抓取并找到一个特定的字符串。一旦发现我拿起那个字符串并保存。返回的字符串显示为User does not have a desktop configured.或法语为L'utilisateur ne dispose pas d'un bureau configuré.,但实际上显示为:L**\x26#39**;utilisateur ne dispose pas d**\x26#39**;un bureau configur**�**.我怎样才能将它考虑为\x26#39作为撇号'字符。试图将字符串转换为正确的格式/编码?

C#中是否有东西可以用来读取Url并返回正确的短语。

我看过很多可用的C#功能,但找不到能够为我提供正确结果的功能。

示例代码试图用玩:

// translated the true French text to English to help out with this example. 
// 
Encoding winVar1252 = Encoding.GetEncoding(1252); 
Encoding utf8 = Encoding.UTF8; 
Encoding ascii = Encoding.ASCII; 
Encoding unicode = Encoding.Unicode; 

string url = String.Format("http://www.My-TEST-SITE.com/); 
WebClient webClient = new WebClient(); 
webClient.Encoding = System.Text.Encoding.UTF8; 
string result = webClient.DownloadString(url); 
cVar = result.Substring(result.IndexOf("Search_TEXT=")).Length ; 
result = result.Substring(result.IndexOf("Search_TEXT="), cVar); 
result = WebUtility.HtmlDecode(result); 
result = WebUtility.UrlDecode(result); 
result = result.Substring(0, result.IndexOf("Found: ")); 

这将返回L**\x26#39**;utilisateur ne dispose pas d**\x26#39**;un bureau configur**�**. 时,它应该返回:L'utilisateur ne dispose pas d'un bureau configuré.

我试图摆脱\x26#39,并得到适当的法国字符显示为é ê è ç â

+0

您不希望使用适当的工具如HtmlAgilityPack进行网络疤痕的任何特定原因? –

+4

你在混合很多东西。基本上,UTF8是字符编码的方式,Unicode是表示法。我建议你先阅读这篇令人惊叹的文章,然后你就会明白发生了什么。 http://www.joelonsoftware.com/articles/Unicode.html –

+0

我不知道“HtmlAgilityPack”,现在阅读文档。至于Joel的网站......是的,我已经看到它,但它并没有告诉我为什么我仍然在我的屏幕上看不到任何UTF8代码。试图找到完美的代码来给我正确的文本。 – user3147056

回答

0

我不能肯定,但:

result = result.Substring(result.IndexOf("Search_TEXT="), cVar); 
result = WebUtility.HtmlDecode(result); 
result = WebUtility.UrlDecode(result); 

双解码文本不能很好。它可能是URL或HTML,也可能都不是。不是都。

+0

尝试过:result = WebUtility.HtmlDecode(result); // result = WebUtility.UrlDecode(result);然后//结果= WebUtility.HtmlDecode(result); result = WebUtility.UrlDecode(result); UrlDecode单独给了我一个字符串大小的错误。 – user3147056

0

它看起来像你的第一个问题不是与字符编码,但与某人的自定义组合"\x" escaped sequence和被遮盖的html entities

那个有趣的**\x26#39**;实际上只是一个简单的单引号。翻译的十六进制字符\x26变为&,因此您可以获得**&#39**;。删除无关的星星,你会得到html实体'。随着HtmlDecode这成为简单的撇号,',这只是ascii字符39.

试试这个片段。请注意,只有最后一步我们才能够执行HtmlDecode。

var input = @"L**\x26#39**;utilisateur ne dispose pas d**\x26#39**;un bureau configur**�**"; 

var result = Regex.Replace(input, @"\*\*([^*]*)\*\*", "$1"); // Take out the extra stars 

// Unescape \x values 
result = Regex.Replace(result, 
         @"\\x([a-fA-F0-9]{2})", 
         match => char.ConvertFromUtf32(Int32.Parse(match.Groups[1].Value, 
                    System.Globalization.NumberStyles.HexNumber))); 

// Decode html entities 
result = System.Net.WebUtility.HtmlDecode(result); 

输出为L'utilisateur ne dispose pas d'un bureau configur�

第二个问题是重音 “E”。这实际上是一个编码问题,你可能不得不继续玩弄它,以使其正确。您可能还想尝试使用UTF16或甚至UTF32。但HtmlAgilityPack可能会自动为您处理这个问题。

相关问题