2013-02-12 53 views
1

我想弄清楚如何使用充满缩写的文本文件来证明和自动更正关键字列表。例如,可能我看起来像这样在我的文本框的列表:使用文件文本来证明文本框

nec 1080p television 
nec hdtv television 
nec lcd tv 
etc. 

而且在我的文本文件,我想有这样的事情:

LCD 
TV 
NEC 
HDTV 
etc. 

什么是最快和最将首字母缩写文本文件与文本框文本(每个文本文本可能长达100行)进行比较的有效方法,并更正文本框中的任何非大写文本?有任何想法吗?

+0

是仅仅使它们全部大写还是拼写更正的问题? – AbZy 2013-02-12 20:06:07

+0

它只是使它们成为大写字母,相对于原始列表。 – Jeagr 2013-02-12 20:16:11

+0

因此,如果电视不在原始列表中,它应该保持不变? – AbZy 2013-02-12 20:18:06

回答

1
textBox.Lines = ReplaceWithAcronyms(textBox.Lines, File.ReadAllLines(acronymsPath)).ToArray(); 

private static IEnumerable<string> ReplaceWithAcronyms(IEnumerable<string> lines, IEnumerable<string> acronyms) 
{ 
    foreach (string line in lines) 
    { 
     yield return string.Join(" ", 
      line.Split(' ').Select(word => ReplaceWithAcronym(word, acronyms))); 
    } 
} 

private static string ReplaceWithAcronym(string word, IEnumerable<string> acronyms) 
{ 
    string acronym = acronyms.FirstOrDefault(ac => ac == word.ToUpperInvariant()); 
    if (acronym == null) 
    { 
     return word; 
    } 

    return acronym; 
} 

ReplaceWithAcronyms取文本框的行和文件的行,其中每行是一个首字母缩写词。 然后它将每行分割成单词并将每个单词传递给ReplaceWithAcronym。如果该单词是其中一个缩写词,它将返回,否则它将返回不变的单词。 通过使用string.Join,单词是“未被分离的”。结果转换为数组,然后分配回文本框行。

我没有检查数百行的速度。为了提高性能,您可以使用HashSet作为首字母缩略词。我不认为几百行是真的有问题。在尝试提高性能之前,我会试试看。也许它已经够好了。

+1

我建议使用[StringComparison.OrdinalIgnoreCase](http://msdn.microsoft.com/zh-cn/ com/en-us/library/system.stringcomparison.aspx)。 'string.Compare(string1,string2,StringComparison.OrdinalIgnoreCase);' – 2013-02-12 21:58:13

+0

Bob,你为什么选择它,它会去哪里? – Jeagr 2013-02-13 01:44:27

+0

它工作完美,Pescolino。谢谢。 – Jeagr 2013-02-13 02:12:36

0

这是我用来最终得到它的工作。我使用了Pescolino的解决方案,然后将其命名为:

sortBox1 = ReplaceWithAcronyms(sortBox1, File.ReadAllLines(@"I:\acronyms.txt")).ToList();