2014-06-24 56 views
-1

我正在尝试编写一个带有文本文件的脚本,并将其读取以查找任何重复的值。下面的代码将重复项写入文本文件,并将重复项的值写入文本文件。但是,我将如何在没有任何重复值的情况下写入值。如何在文本文件中找到重复项并将没有重复项的值写入文本文件?

Const ForReading = 1 
Const ForWriting = 2 
Set objFSO = CreateObject("Scripting.FileSystemObject") 
Set objFile = objFSO.OpenTextFile("C:\Users\A352592\Desktop\predata.txt", 

ForReading) 
Set objOutputFile = objFSO.OpenTextFile("C:\Users\A352592\Desktop 

\Noduplicates.txt", 2, True) 
Set objOutputFile2 = objFSO.OpenTextFile("C:\Users\A352592\Desktop 

\Duplicates.txt", 2, True) 
Set objOutputFile3 = objFSO.OpenTextFile("C:\Users\A352592\Desktop 

\alone.txt", 2, True) 
Set Dict = CreateObject("Scripting.Dictionary") 
Do until objFile.atEndOfStream 
    strCurrentLine = objFile.ReadLine 
    If not Dict.Exists(strCurrentLine) then 
     objOutputFile.WriteLine strCurrentLine 
     Dict.Add strCurrentLine,strCurrentLine 
    ElseIf Dict.Exists(strCurrentLine) then 
     objOutputFile2.WriteLine strCurrentLine 

    Else 
     objOutputFile3.WriteLine strCurrentLine 
    End if 
Loop 
wscript.echo "Finished" 

回答

1

在阅读输入时,您无法在飞行/不使用dups的情况下检测/写入独特/榆树 - 最后一行可能会使元素不唯一。因此,计数在输入循环中的元素,然后将分类的元素写入不同的文件。

代码来说明:

>> a = Split("a b c a b b") 
>> Set d = CreateObject("Scripting.Dictionary") 
>> For Each e In a 
>>  d(e) = d(e) + 1 
>> Next 
>> 
>> For Each e In d.Keys 
>>  WScript.Echo d(e), e 
>> Next 
>> 
2 a 
3 b 
1 c 
1

保留关联字典条目的计数。每当你匹配一条线时,增加它在字典中的数量。读完文件后,再次查看字典并输出每一行的计数为1.

或者,您可以对文件进行排序并按顺序执行。我的VBScript技能已经萎缩,但总体思路是:

string prevLine = read first line 
bool isDup = false 
for each remaining line 
    if (line != prevLine) 
     if (!isDup) 
      line has no duplicates 
     prevLine = line 
     isDup = false 
    else 
     isDup = true 

排序的文件,看看该Windows SORT program

如果您可以安装GNU/Linux公用程序,请查看sortuniq。他们会让你这样做,而不必编写任何代码。

相关问题