原理:通过C#获取要查词汇的网页数据,根据关键字截取需要的解释,并显示出来。
图形界面设计:
源码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;
namespace WindowsForms
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void en_to_ch(object sender, EventArgs e)
{
try
{
textBox1.Text = "";
if (m_word.Text.Trim() == "")
{
textBox1.Text = " 无结果";
return;
}
WebClient MyWebClient = new WebClient();
MyWebClient.Credentials = CredentialCache.DefaultCredentials;//获取或设置用于向Internet资源的请求进行身份验证的网络凭据
string url = "http://dict.youdao.com/search?q=" + m_word.Text.Trim();
Byte[] pageData = MyWebClient.DownloadData(url); //从指定网站下载数据
//string pageHtml = Encoding.Default.GetString(pageData); //如果获取网站页面采用的是GB2312,则使用这句
//StreamReader sr = new System.IO.StreamReader(pageData, System.Text.Encoding.UTF8);
string pageHtml = Encoding.UTF8.GetString(pageData); //如果获取网站页面采用的是UTF-8,则使用这句
//using (StreamWriter sw = new StreamWriter("output1.html"))//将获取的内容写入文本
//{
// sw.Write(pageHtml);
//}
//get pronounce
string pronstr = pageHtml;
int p1 = pronstr.IndexOf("\"phonetic\"");
string phone = "";
if (p1 > 0)
{
pronstr = pronstr.Substring(p1 + 11);
int p2 = pronstr.IndexOf("");
if (p2 > 0)
{
phone = " 英:";
phone += pronstr.Substring(0, p2) + " ";
}
// MessageBox.Show(p1.ToString());
}
// else
// m_word.Text = p1.ToString();--内容结束--
p1 = pronstr.IndexOf("\"phonetic\"");
if (p1 > 0)
{
pronstr = pronstr.Substring(p1 + 11);
int p2 = pronstr.IndexOf("");
if (p2 > 0)
phone += "美:" + pronstr.Substring(0, p2) + "\r\n";
}
int pos = pageHtml.IndexOf("class=\"trans-container\"");
if (pos == -1)
{
textBox1.Text = "无结果";
return;
}
int pauth = pageHtml.IndexOf("\"trans-container\" id=\"authDictTrans\"");
if (pauth > 0)
{
int pend = pageHtml.IndexOf("--内容结束--");
string sauth = pageHtml.Substring(pauth + 50, pend - pauth);
while (true)
{
int pl = sauth.IndexOf("<");
if (pl == -1)
break;
int pr = sauth.IndexOf(">");
if (pr == -1)
break;
if (pl < pr)
sauth = sauth.Remove(pl, pr - pl + 1);
else
break;
}
char[] sep = { '\r' };
string[] arr1;
arr1 = sauth.Split(sep); //分解为数组
sauth = "";
foreach (string i in arr1)
{
sauth += " " + i.Trim();
}
sauth = Regex.Replace(sauth, @"\s+", " ");
sauth = sauth.Replace("。", "。\r\n");
sauth = sauth.Replace(".", ".\r\n");
sauth = sauth.Replace(",", ", ");
sauth = sauth.Replace(",", ", ");
textBox1.Text = sauth.Trim();
return;
}
string container = pageHtml.Substring(pos + 25); //截取开始str
int posdiv = container.IndexOf("