編寫一個程序,對文本文件中的短語進行計數。任何字符序列都可以作爲用於計數的短語給出,甚至包含分隔符的序列。例如,在「我是索非亞的學生」的文本中,短語「s」,「stu」,「a」和「我是」分別被找到2,1,3和1次。
我知道有string.IndexOf或LINQ或一些類似阿霍Corasick型算法的解決方案。我想用Regex做同樣的事情。
這是我迄今所做的:
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
namespace CountThePhrasesInATextFile
{
class Program
{
static void Main(string[] args)
{
string input = ReadInput("file.txt");
input.ToLower();
List<string> phrases = new List<string>();
using (StreamReader reader = new StreamReader("words.txt"))
{
string line = reader.ReadLine();
while (line != null)
{
phrases.Add(line.Trim());
line = reader.ReadLine();
}
}
foreach (string phrase in phrases)
{
Regex regex = new Regex(String.Format(".*" + phrase.ToLower() + ".*"));
int mathes = regex.Matches(input).Count;
Console.WriteLine(phrase + " ----> " + mathes);
}
}
private static string ReadInput(string fileName)
{
string output;
using (StreamReader reader = new StreamReader(fileName))
{
output = reader.ReadToEnd();
}
return output;
}
}
}
我知道我的正則表達式是不正確,但我不知道是什麼改變。
輸出:
Word ----> 2
S ----> 2
MissingWord ----> 0
DS ----> 2
aa ----> 0
正確的輸出:
Word --> 9
S --> 13
MissingWord --> 0
DS --> 2
aa --> 3
file.txt的包含:
Word? We have few words: first word, second word, third word.
Some passwords: PASSWORD123, @PaSsWoRd!456, AAaA, !PASSWORD
words.txt包含:
Word
S
MissingWord
DS
aa
「我知道我的正則表達式是不正確」我們永遠不會知道,直到你發佈你的代碼的說法是真實的。我99%肯定它的錯誤 – Steve
請發佈您的'file.txt'內容 –
.NET中的字符串是不可變的。所以需要編寫'input = input.ToLower();' –