我正在处理此代码,在其中可以从列表中找到Web浏览器中的单词。我想计算出现的次数并将其插入数据库的另一列,然后再将这些单词替换为星号。有什么解决办法吗?
这是我的代码:
svchost.exe
答案 0 :(得分:-1)
一种方法是使用正则表达式进行计数和替换:
Dictionary<string,int> counts = new Dictionary<string, int>();
foreach (var word in words)
{
var matches = Regex.Matches(html, $@"\b{word}\b", RegexOptions.IgnoreCase);
counts.Add(word, matches.Count);
html = Regex.Replace(html, $@"\b{word}\b", "".PadLeft(word.Length, '*'), RegexOptions.IgnoreCase);
}
foreach (var kv in counts)
{
Console.WriteLine($"{kv.Key}:{kv.Value}");
}
Console.WriteLine(html);
答案 1 :(得分:-1)
我希望这会有所帮助。
using System;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Xunit;
using Xunit.Abstractions;
namespace CountNumberTest
{
public class WebBrowserReplaceHtmlFromDatabaseTest
{
private const string BaseAddress = "https://stackoverflow.com/questions/52572969/count-number-of-occurrence";
private readonly ITestOutputHelper Output;
private static readonly HttpClient StaticHttpComponent = new HttpClient
{
BaseAddress = new Uri(BaseAddress)
};
public WebBrowserReplaceHtmlFromDatabaseTest(ITestOutputHelper output)
{
this.Output = output;
}
[Fact]
public async Task When_GetHtmlBodyFromWebPage_Then_ReplaceAllWordInHtml()
{
var replaceWordCollection = new[] { "html", "I", "in", "on" };
var request = new HttpRequestMessage(HttpMethod.Get, $"{BaseAddress}");
HttpResponseMessage response = await StaticHttpComponent.SendAsync(request);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
StringBuilder buffer = new StringBuilder(await response.Content.ReadAsStringAsync());
Assert.NotEqual(0, buffer.Length);
foreach (string word in replaceWordCollection)
{
int len = word.Length;
int countOccurrence = Regex.Matches(buffer.ToString(), word).Count;
var replaceWord = new string('*', len);
Output.WriteLine($"{word} - occurred: {countOccurrence}");
buffer.Replace(word, replaceWord);
}
string html = buffer.ToString();
foreach (string word in replaceWordCollection)
Assert.DoesNotContain(word, html);
Output.WriteLine(html);
}
}
}