ImportExerciseService.cs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516
  1. using DocumentFormat.OpenXml.Packaging;
  2. using HtmlAgilityPack;
  3. using Microsoft.AspNetCore.Http;
  4. using OpenXmlPowerTools;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.Drawing.Imaging;
  8. using System.IO;
  9. using System.Linq;
  10. using System.Text;
  11. using System.Text.RegularExpressions;
  12. using System.Threading.Tasks;
  13. using System.Xml.Linq;
  14. using TEAMModelOS.Model.Core.Dtos;
  15. using TEAMModelOS.Model.Core.Models;
  16. using TEAMModelOS.Model.Evaluation.Dtos.Own;
  17. using TEAMModelOS.Model.Evaluation.Models;
  18. using TEAMModelOS.SDK.Context.Configuration;
  19. using TEAMModelOS.SDK.Extension.DataResult.JsonRpcRequest;
  20. using TEAMModelOS.SDK.Extension.SnowFlake;
  21. using TEAMModelOS.SDK.Helper.Common.CollectionHelper;
  22. using TEAMModelOS.SDK.Helper.Common.FileHelper;
  23. using TEAMModelOS.SDK.Helper.Common.JsonHelper;
  24. using TEAMModelOS.SDK.Helper.Common.StringHelper;
  25. using TEAMModelOS.SDK.Helper.Network.HttpHelper;
  26. using TEAMModelOS.SDK.Helper.Security.ShaHash;
  27. using TEAMModelOS.SDK.Module.AzureBlob.Container;
  28. using TEAMModelOS.SDK.Module.AzureBlob.Interfaces;
  29. using TEAMModelOS.SDK.Module.AzureTable.Interfaces;
  30. using TEAMModelOS.Service.Core.Implements;
  31. using TEAMModelOS.Service.Evaluation.Interfaces;
  32. namespace TEAMModelOS.Service.Evaluation.Implements
  33. {
  34. public class ImportExerciseService : BaseService, IImportExerciseService
  35. {
  36. public async Task<Dictionary<string, object>> UploadWord(IFormFile file)
  37. {
  38. Dictionary<string, object> resdict = new Dictionary<string, object>();
  39. string shaCode = ShaHashHelper.GetSHA1(file.OpenReadStream());
  40. long length = file.Length;
  41. Dictionary<string, object> dict = new Dictionary<string, object> { { "Sha1Code", shaCode } };
  42. List<AzureBlobModel> models = await FindListByDict<AzureBlobModel>(dict);
  43. if (models.IsNotEmpty())
  44. {
  45. resdict.Add("HtmlString", HttpHelper.HttpGet(models[0].BlobUrl));
  46. resdict.Add("Sha1Code", models[0].Sha1Code);
  47. return resdict;
  48. }
  49. string folder = BaseConfigModel.ContentRootPath + "/Upload/" + IdWorker.getInstance().NextId();
  50. System.IO.Directory.CreateDirectory(folder);
  51. var filePath = folder +"\\"+ file.FileName;
  52. using (var stream = new FileStream(filePath, FileMode.Create))
  53. {
  54. await file.CopyToAsync(stream);
  55. }
  56. var htmlInfo = ConvertDocxToHtml(filePath, folder);
  57. AzureBlobModel model = await azureBlobDBRepository.UploadPath(htmlInfo.blobPath);
  58. model.Sha1Code = shaCode;
  59. await Save<AzureBlobModel>(model);
  60. FileHelper.DeleteDirAndFiles(BaseConfigModel.ContentRootPath + "/Upload");
  61. resdict.Add("HtmlString", htmlInfo.htmlString);
  62. resdict.Add("Sha1Code", shaCode);
  63. return resdict;
  64. }
  65. public static dynamic ConvertDocxToHtml(string filePath ,string folder)
  66. {
  67. byte[] byteArray = File.ReadAllBytes(filePath);
  68. //byte[] bytes = new byte[stream.Length];
  69. using (MemoryStream memoryStream = new MemoryStream())
  70. {
  71. memoryStream.Write(byteArray, 0, byteArray.Length);
  72. using (WordprocessingDocument doc = WordprocessingDocument.Open(memoryStream, true))
  73. {
  74. int imageCounter = 0;
  75. WmlToHtmlConverterSettings settings = new WmlToHtmlConverterSettings()
  76. {
  77. PageTitle = "My Page Title",
  78. AdditionalCss = "body { margin: 1cm auto; max-width: 20cm; padding: 0; }",
  79. FabricateCssClasses = true,
  80. CssClassPrefix = "pt-",
  81. RestrictToSupportedLanguages = false,
  82. RestrictToSupportedNumberingFormats = false,
  83. ImageHandler = imageInfo =>
  84. {
  85. ++imageCounter;
  86. string extension = imageInfo.ContentType.Split('/')[1].ToLower();
  87. ImageFormat imageFormat = null;
  88. if (extension == "png") imageFormat = ImageFormat.Png;
  89. else if (extension == "gif") imageFormat = ImageFormat.Gif;
  90. else if (extension == "bmp") imageFormat = ImageFormat.Bmp;
  91. else if (extension == "jpeg") imageFormat = ImageFormat.Jpeg;
  92. else if (extension == "tiff")
  93. {
  94. extension = "gif";
  95. imageFormat = ImageFormat.Gif;
  96. }
  97. else if (extension == "x-wmf")
  98. {
  99. extension = "wmf";
  100. imageFormat = ImageFormat.Wmf;
  101. }
  102. if (imageFormat == null) return null;
  103. string base64 = null;
  104. try
  105. {
  106. using (MemoryStream ms = new MemoryStream())
  107. {
  108. imageInfo.Bitmap.Save(ms, imageFormat);
  109. var ba = ms.ToArray();
  110. base64 = System.Convert.ToBase64String(ba);
  111. }
  112. }
  113. catch (System.Runtime.InteropServices.ExternalException)
  114. { return null; }
  115. ImageFormat format = imageInfo.Bitmap.RawFormat;
  116. ImageCodecInfo codec = ImageCodecInfo.GetImageDecoders()
  117. .First(c => c.FormatID == format.Guid);
  118. string mimeType = codec.MimeType;
  119. string imageSource =
  120. string.Format("data:{0};base64,{1}", mimeType, base64);
  121. XElement img = new XElement(Xhtml.img,
  122. new XAttribute(NoNamespace.src, imageSource),
  123. imageInfo.ImgStyleAttribute,
  124. imageInfo.AltText != null ?
  125. new XAttribute(NoNamespace.alt, imageInfo.AltText) : null);
  126. return img;
  127. }
  128. };
  129. // XElement html = HtmlConverter.ConvertToHtml(doc, settings);
  130. // File.WriteAllText(@"E:\document\kk.html", html.ToStringNewLineOnAttributes());
  131. XElement htmlElement = WmlToHtmlConverter.ConvertToHtml(doc, settings);
  132. var htmls = new XDocument(new XDocumentType("html", null, null, null), htmlElement);
  133. var htmlString = htmls.ToString(SaveOptions.DisableFormatting);
  134. //引入MathJax插件
  135. htmlString = htmlString + "<script type=\"text/javascript\" src=\"http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML\"></script>";
  136. File.WriteAllText(folder+"/"+"index.html", htmlString);
  137. return new { htmlString ,blobPath= folder + "/" + "index.html" };
  138. };
  139. }
  140. }
  141. private static string SummaryTag = "【题文】";
  142. private static string AnswerTag = "【答案】";
  143. private static string AnalysisTag = "【解析】";
  144. private static string EndedTag = "【结束】";
  145. private static string Options = "ABCDEFGHIJ";
  146. private static string CompleteStart = "【";
  147. private static string CompleteEnd = "】";
  148. Dictionary<string, string> TestType = new Dictionary<string, string> {
  149. { "Single", "单选题|多选题" }, { "Multiple", "多选题|判断题" },
  150. { "Judge", "判断题|填空题" }, { "Complete", "填空题|主观题" },
  151. { "Subjective", "主观题|【完结】" } };
  152. //private readonly IAzureTableDBRepository azureTableDBRepository;
  153. private readonly IHttpContextAccessor httpContextAccessor;
  154. private readonly IAzureBlobDBRepository azureBlobDBRepository;
  155. public ImportExerciseService(IHttpContextAccessor _httpContextAccessor , IAzureBlobDBRepository _azureBlobDBRepository)
  156. {
  157. azureBlobDBRepository = _azureBlobDBRepository;
  158. httpContextAccessor = _httpContextAccessor;
  159. }
  160. public async Task<List<ExerciseDto>> AnalyzeWordAsync(DocInfoDto dict, string Lang)
  161. {
  162. List<ContentVerify> contents = await this.FindListByKey<ContentVerify>("DigestCode", dict.ShaCode);
  163. string html;
  164. if (contents.IsNotEmpty())
  165. {
  166. html = contents[0].Content;
  167. }
  168. else
  169. {
  170. string Word2html = BaseConfigModel.Configuration["HaBookAuth:Word2html"];
  171. JosnRPCRequest<DocInfoDto> request = new JosnRPCRequest<DocInfoDto>();
  172. request.@params = dict;
  173. string jsondata = MessagePackHelper.ObjectToJson(request);
  174. html = await HttpHelper.HttpPostAsync(Word2html, jsondata);
  175. ContentVerify content = new ContentVerify { RowKey = dict.ShaCode, PartitionKey = Lang, AlgorithmType = "Sha1", Content = html, DigestCode = dict.ShaCode };
  176. await this.SaveOrUpdate<ContentVerify>(content);
  177. }
  178. //String url = "https://teammodelstorage.blob.core.chinacloudapi.cn/teammodelcontest/20190517/%E6%A8%A1%E6%9D%BF%E6%A0%B7%E4%BE%8B.doc";
  179. Dictionary<string, string> TestInType = new Dictionary<string, string>();
  180. html = html.Replace("\t", " ").Replace("<span>", "").Replace("</span>", "");
  181. //去除class
  182. string classpattern = "class=\"([^\"]*)\"";
  183. html = Regex.Replace(html, classpattern, "");
  184. string pattern = "<span([^>]{0,})>";
  185. html = Regex.Replace(html, pattern, "");
  186. foreach (string key in TestType.Keys)
  187. {
  188. string[] tags = TestType[key].Split("|");
  189. string RegexStr = tags[0] + "([\\s\\S]*?)" + tags[1];
  190. Match mt = Regex.Match(html, RegexStr);
  191. TestInType.Add(key, mt.Value);
  192. }
  193. List<ExerciseDto> tests = new List<ExerciseDto>();
  194. ///解析几种题型的题目
  195. foreach (string key in TestInType.Keys)
  196. {
  197. switch (key)
  198. {
  199. case "Single":
  200. List<ExerciseDto> exercisesSingle = SingleConvert(key, TestInType[key]);
  201. tests.AddRange(exercisesSingle); break;
  202. case "Multiple":
  203. List<ExerciseDto> exercisesMultiple = MultipleConvert(key, TestInType[key]);
  204. tests.AddRange(exercisesMultiple); break;
  205. case "Judge":
  206. List<ExerciseDto> exercisesJudge = JudgeConvert(key, TestInType[key]);
  207. tests.AddRange(exercisesJudge); break;
  208. case "Complete":
  209. List<ExerciseDto> exercisesComplete = CompleteConvert(key, TestInType[key]);
  210. tests.AddRange(exercisesComplete); break;
  211. case "Subjective":
  212. List<ExerciseDto> exercisesSubjective = SubjectiveConvert(key, TestInType[key]);
  213. tests.AddRange(exercisesSubjective); break;
  214. default: break;
  215. }
  216. }
  217. SaveExercise(tests, Lang);
  218. return tests;
  219. }
  220. public async void SaveExercise(List<ExerciseDto> exercises, string Lang)
  221. {
  222. string tmdid = "";
  223. List<string> ids = HttpContextHelper.GetLoginUser(httpContextAccessor, "id");
  224. if (ids.IsNotEmpty())
  225. {
  226. tmdid = ids[0];
  227. }
  228. List<ExerciseVerify> exerciseVerifies = new List<ExerciseVerify>();
  229. exercises.ForEach(x =>
  230. {
  231. ExerciseVerify exercise0 = new ExerciseVerify { TeamModelId = tmdid, RowKey = x.ShaCode, Type = 0, PartitionKey = Lang, Content = x.Question, SummaryCode = x.ShaCode, Status = 1 };
  232. exerciseVerifies.Add(exercise0);
  233. if (x.Option.IsNotEmpty())
  234. {
  235. string opt = MessagePackHelper.ObjectToJson(x.Option);
  236. ExerciseVerify exercise1 = new ExerciseVerify { TeamModelId = tmdid, RowKey = x.ShaCode + "-" + ShaHashHelper.GetSHA1(opt), Type = 1, PartitionKey = Lang, Content = opt, SummaryCode = x.ShaCode, Status = 1 };
  237. exerciseVerifies.Add(exercise1);
  238. }
  239. if (x.Answer.IsNotEmpty())
  240. {
  241. string ans = MessagePackHelper.ObjectToJson(x.Answer);
  242. ExerciseVerify exercise2 = new ExerciseVerify { TeamModelId = tmdid, RowKey = x.ShaCode + "-" + ShaHashHelper.GetSHA1(ans), Type = 2, PartitionKey = Lang, Content = ans, SummaryCode = x.ShaCode, Status = 1 };
  243. exerciseVerifies.Add(exercise2);
  244. }
  245. ExerciseVerify exercise3 = new ExerciseVerify { TeamModelId = tmdid, RowKey = x.ShaCode + "-" + ShaHashHelper.GetSHA1(x.Explain), Type = 3, PartitionKey = Lang, Content = x.Explain, SummaryCode = x.ShaCode, Status = 1 };
  246. exerciseVerifies.Add(exercise3);
  247. });
  248. await this.SaveOrUpdateAll(exerciseVerifies);
  249. }
  250. public static List<ExerciseDto> SingleConvert(string TypeKey, string testHtml)
  251. {
  252. List<ExerciseDto> testInfos = OptionProcess(TypeKey, testHtml);
  253. return testInfos;
  254. }
  255. public static List<ExerciseDto> MultipleConvert(string TypeKey, string testHtml)
  256. {
  257. List<ExerciseDto> testInfos = OptionProcess(TypeKey, testHtml);
  258. return testInfos;
  259. }
  260. public static List<ExerciseDto> JudgeConvert(string TypeKey, string testHtml)
  261. {
  262. List<ExerciseDto> testInfos = OptionProcess(TypeKey, testHtml);
  263. return testInfos;
  264. }
  265. public static List<ExerciseDto> CompleteConvert(string TypeKey, string testHtml)
  266. {
  267. List<ExerciseDto> testInfos = CompleteProcess(TypeKey, testHtml);
  268. return testInfos;
  269. }
  270. public static List<ExerciseDto> SubjectiveConvert(string TypeKey, string testHtml)
  271. {
  272. List<string> tests = ConvertTest(testHtml);
  273. List<ExerciseDto> testInfos = ConvertTestInfo(tests, TypeKey);
  274. foreach (ExerciseDto testInfo in testInfos)
  275. {
  276. testInfo.Question = testInfo.Question.Replace(AnalysisTag, "").Replace(SummaryTag, "").Replace(AnswerTag, "");
  277. testInfo.Question = HtmlHelper.DoUselessTag(testInfo.Question);
  278. StringBuilder textImg = new StringBuilder(HtmlHelper.DoTextImg(testInfo.Question));
  279. testInfo.ShaCode = ShaHashHelper.GetSHA1(textImg.ToString());
  280. for (int i = 0; i < testInfo.Answer.Count; i++)
  281. {
  282. testInfo.Answer[i] = testInfo.Answer[i].Replace(AnswerTag, "").Replace(AnalysisTag, "");
  283. testInfo.Answer[i] = HtmlHelper.DoUselessTag(testInfo.Answer[i]);
  284. }
  285. testInfo.Explain = testInfo.Explain.Replace(AnalysisTag, "").Replace(EndedTag, "");
  286. testInfo.Explain = HtmlHelper.DoUselessTag(testInfo.Explain);
  287. }
  288. return testInfos;
  289. }
  290. public static List<ExerciseDto> CompleteProcess(string TypeKey, string testHtml)
  291. {
  292. List<string> tests = ConvertTest(testHtml);
  293. List<ExerciseDto> testInfos = ConvertTestInfo(tests, TypeKey);
  294. HtmlDocument doc = new HtmlDocument();
  295. foreach (ExerciseDto testInfo in testInfos)
  296. {
  297. List<string> ans = new List<string>();
  298. testInfo.Question = testInfo.Question.Replace(AnalysisTag, "").Replace(SummaryTag, "").Replace(AnswerTag, "");
  299. string regRex = CompleteStart + "([\\s\\S]*?)" + CompleteEnd;
  300. List<ReplaceDto> replaces = new List<ReplaceDto>();
  301. var m = Regex.Match(testInfo.Question, regRex);
  302. int index = 1;
  303. while (m.Success)
  304. {
  305. string an = m.Groups[1].ToString();
  306. doc.LoadHtml(an);
  307. string anstr = doc.DocumentNode.InnerText;
  308. string nbsp = "";
  309. int length = System.Text.Encoding.Default.GetBytes(anstr).Length;
  310. for (int i = 0; i < length * 3; i++)
  311. {
  312. nbsp += "&nbsp;";
  313. }
  314. ReplaceDto replaceDto = new ReplaceDto { oldstr = "【" + an + "】", newstr = "<underline data=\"" + index + "\"><u>" + nbsp + "</u></underline>" };
  315. replaces.Add(replaceDto);
  316. ans.Add(an);
  317. m = m.NextMatch();
  318. index++;
  319. }
  320. string textImg = testInfo.Question;
  321. //消除答案
  322. foreach (ReplaceDto replace in replaces)
  323. {
  324. testInfo.Question = testInfo.Question.Replace(replace.oldstr, replace.newstr);
  325. testInfo.Question = HtmlHelper.DoUselessTag(testInfo.Question);
  326. //只要题干文字和图片
  327. //不加underline标记
  328. textImg = testInfo.Question.Replace(replace.oldstr, "");
  329. }
  330. textImg = HtmlHelper.DoTextImg(textImg);
  331. testInfo.ShaCode = ShaHashHelper.GetSHA1(textImg);
  332. //处理解析
  333. testInfo.Explain = testInfo.Explain.Replace(AnalysisTag, "").Replace(EndedTag, "");
  334. testInfo.Explain = HtmlHelper.DoUselessTag(testInfo.Explain);
  335. testInfo.Answer.AddRange(ans);
  336. }
  337. return testInfos;
  338. }
  339. /// <summary>
  340. /// 选择题处理
  341. /// </summary>
  342. /// <param name="TypeKey"></param>
  343. /// <param name="testHtml"></param>
  344. /// <returns></returns>
  345. public static List<ExerciseDto> OptionProcess(string TypeKey, string testHtml)
  346. {
  347. //处理 \t
  348. List<string> tests = ConvertTest(testHtml);
  349. string[] optionsKeys = Options.Select(s => s.ToString()).ToArray();
  350. List<ExerciseDto> testInfos = ConvertTestInfo(tests, TypeKey);
  351. foreach (ExerciseDto testInfo in testInfos)
  352. {
  353. string optsRgex = optionsKeys[0] + "(\\.|\\.|\\、|\\:|\\:)([\\s\\S]*?)" + AnswerTag;
  354. string optsHtml = Regex.Match(testInfo.Question, optsRgex).Value;
  355. //HtmlDocument doc = new HtmlDocument();
  356. //doc.LoadHtml(optsHtml);
  357. //optsHtml = doc.DocumentNode.InnerText;
  358. //处理选项
  359. StringBuilder textImg = new StringBuilder();
  360. for (int i = 0; i < optionsKeys.Length - 1; i++)
  361. {
  362. string optRgex = optionsKeys[i] + "(\\.|\\.|\\、|\\:|\\:)([\\s\\S]*?)" + optionsKeys[i + 1] + "(\\.|\\.|\\、|\\:|\\:)";
  363. string optHtml = Regex.Match(optsHtml, optRgex).Value;
  364. if (!string.IsNullOrEmpty(optHtml))
  365. {
  366. optHtml = optHtml.Substring(2, optHtml.Length - 4);
  367. optHtml = HtmlHelper.DoUselessTag(optHtml);
  368. textImg.Append(HtmlHelper.DoTextImg(optHtml));
  369. testInfo.Option.Add(new CodeValue { Code = optionsKeys[i], Value = optHtml });
  370. //testInfo.Option.Add(new Dictionary<string, string> { { "code", optionsKeys[i] },{ "value", optHtml } });
  371. //testInfo.Option.TryAdd(optionsKeys[i], optHtml);
  372. }
  373. else
  374. {
  375. optRgex = optionsKeys[i] + "(\\.|\\.|\\、|\\:|\\:)([\\s\\S]*?)" + AnswerTag;
  376. optHtml = Regex.Match(optsHtml, optRgex).Value;
  377. if (!string.IsNullOrEmpty(optHtml))
  378. {
  379. optHtml = optHtml.Substring(2, optHtml.Length - 6);
  380. optHtml = HtmlHelper.DoUselessTag(optHtml);
  381. textImg.Append(HtmlHelper.DoTextImg(optHtml));
  382. testInfo.Option.Add(new CodeValue { Code = optionsKeys[i], Value = optHtml });
  383. //testInfo.Option.Add(new Dictionary<string, string> { { "code", optionsKeys[i] }, { "value", optHtml } });
  384. //testInfo.Option.TryAdd(optionsKeys[i], optHtml);
  385. }
  386. }
  387. }
  388. //处理题干
  389. testInfo.Question = testInfo.Question.Replace(optsHtml, "").Replace(SummaryTag, "").Replace(AnswerTag, "");
  390. testInfo.Question = HtmlHelper.DoUselessTag(testInfo.Question);
  391. textImg.Append(HtmlHelper.DoTextImg(testInfo.Question));
  392. testInfo.ShaCode = ShaHashHelper.GetSHA1(textImg.ToString());
  393. List<string> answers = testInfo.Answer;
  394. HashSet<string> ans = new HashSet<string>();
  395. //处理答案
  396. for (int i = 0; i < answers.Count; i++)
  397. {
  398. string Answer = answers[i].Replace(AnswerTag, "").Replace(AnalysisTag, "").TrimStart().TrimEnd();
  399. Answer.Select(s => s.ToString()).ToList().ForEach(x =>
  400. {
  401. ans.Add(x);
  402. });
  403. }
  404. testInfo.Answer = ans.ToList();
  405. //处理解析
  406. testInfo.Explain = testInfo.Explain.Replace(AnalysisTag, "").Replace(EndedTag, "");
  407. testInfo.Explain = HtmlHelper.DoUselessTag(testInfo.Explain);
  408. }
  409. return testInfos;
  410. }
  411. public static List<ExerciseDto> ConvertTestInfo(List<string> tests, string TypeKey)
  412. {
  413. List<ExerciseDto> testInfos = new List<ExerciseDto>();
  414. foreach (string html in tests)
  415. {
  416. Dictionary<string, string> regex = new Dictionary<string, string>();
  417. Dictionary<string, string> question = new Dictionary<string, string> { { "Summary", SummaryTag + "|" + AnswerTag }, { "Answer", AnswerTag + "|" + AnalysisTag }, { "Analysis", AnalysisTag + "|" + EndedTag } };
  418. Dictionary<string, string> compquestion = new Dictionary<string, string> { { "Summary", SummaryTag + "|" + AnalysisTag }, { "Analysis", AnalysisTag + "|" + EndedTag } };
  419. ExerciseDto test = new ExerciseDto();
  420. test.Type = TypeKey;
  421. List<string> keys = new List<string>();
  422. if (TypeKey.Equals("Complete"))
  423. {
  424. keys = compquestion.Keys.ToList();
  425. regex = compquestion;
  426. }
  427. else
  428. {
  429. keys = question.Keys.ToList();
  430. regex = question;
  431. }
  432. foreach (string key in keys)
  433. {
  434. string[] tags = regex[key].Split("|");
  435. string RegexStr = tags[0] + "([\\s\\S]*?)" + tags[1];
  436. Match mt = Regex.Match(html, RegexStr);
  437. switch (key)
  438. {
  439. case "Summary":
  440. test.Question = mt.Value; break;
  441. case "Answer":
  442. string Answer = mt.Value;
  443. ///单选或多选,判断答案 脱html标签
  444. if (TypeKey.Equals("Single") || TypeKey.Equals("Multiple") || TypeKey.Equals("Judge"))
  445. {
  446. HtmlDocument doc = new HtmlDocument();
  447. doc.LoadHtml(mt.Value);
  448. Answer = doc.DocumentNode.InnerText;
  449. }
  450. test.Answer = new List<string>() { Answer }; break;
  451. case "Analysis":
  452. test.Explain = mt.Value; break;
  453. default: break;
  454. }
  455. }
  456. testInfos.Add(test);
  457. }
  458. return testInfos;
  459. }
  460. public static List<string> ConvertTest(string testHtml)
  461. {
  462. string start = SummaryTag;
  463. string end = EndedTag;
  464. List<string> tests = new List<string>();
  465. while (testHtml.IndexOf(start) > 0)
  466. {
  467. int indexStart = testHtml.IndexOf(start);
  468. int indexEnd = testHtml.IndexOf(end);
  469. string test = testHtml.Substring(indexStart, indexEnd - indexStart + start.Length);
  470. tests.Add(test);
  471. testHtml = testHtml.Substring(indexEnd + end.Length);
  472. }
  473. return tests;
  474. }
  475. }
  476. class ReplaceDto
  477. {
  478. public string oldstr { get; set; }
  479. public string newstr { get; set; }
  480. }
  481. }