比较文本文件 - 使用VBscripting注销一些文本 [英] Compare text files - Igonring some texts using VBscripting

查看:214
本文介绍了比较文本文件 - 使用VBscripting注销一些文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,我不是从编程背景和完全新的VBscript。由于某些原因,我必须在办公室做这个脚本任务。
我想要与Quick Test Professional 11一起使用。



我在这里经历了很多帖子以及其他论坛,但是找不到所需的信息。



好的,这里是我需要做的:



我必须比较两个文本文件,差异在第三文件。
这两个文件在某些​​字段中具有几乎相同的内容aprt,例如:Date,Order no等。



例如,File-1有Date: 00/11/1234和订单号:1111和文件2有日期:11/00/6789和订单号:2222
有什么办法,我可以忽略这些字段及其值?
有没有办法,我可以创建忽略列表,我可以添加和哪些将在比较期间使用,并将在比较过程中跳过字段?
所以我的差异文件不会有这些差异,因为这些值总是不同的。
所以我可以得到我的结果文件中的所有其他差异。



为了参考,这里是示例文件。



到目前为止,我已经比较了这两个文件,但是以最简单的方式,我不知道如何忽略字段。
我想将这些任务作为一个函数,以便我可以在我的函数库中使用它。



File-1 / p>

日期:00/11/1234 /订单号:1111



价格1:$ 1111.00



价格2:$ 2222.00



价格3:$ 1234.00



GHI kjl 1111



订单编号:1111



期限:2年



日期:00/11/1234



File-2



日期:11/00/6789和订单号:2222



价格1:$ 1111.00



价格2:$ 2222.00



价格3:$ 5678.00



ABC def GHI kjl 1111



订单号:2222



期限:3年



日期:11 / 00/6789



结果文件应显示



p>

档案1第4行:价格3:$ 1234.00



档案2第4行:价格3:$ 5678.00

档案1第7行:期限:2年



档案2第7行:期限:3年



非常感谢。



Hi @ Ekkehard.Horner
非常感谢你的帮助和时间,并容忍我的sily问题。
事实是,我越努力理解你的代码,我越困惑。
当我把这下面的代码在Quick Test Pro_11,它抛出我的语法错误@Dim oDiffer:Set oDiffer = New cDiffer.init(C:......
QTP is saying ... New cDiffer和.init之间的期望的结束
QTP在函数TrailVersion以及函数GoldVersion中显示错误



这将是非常好的,如果你会抛出一些光这个
和是否有必要有预期文本文件...?因为我不想包括该部分,因为否则我必须为每次比较创建预期文件。



请原谅我的sily问题。



 类cDiffer 
选项显式
Dim goFS:设置goFS = CreateObject Scripting.FileSystemObject)
WScript.Quit TrialVersion()
WScript.Quit TinVersion()
功能TinVersion()
WScript.Echo无法比较文件
TinVersion = 1
结束函数'TinVersion
这里我提供了试用版功能
功能TrialVersion()
Dim oDiffer:Set oDiffer = New cDiffer.init :\Documents and Settings\24800 \My Documents \PDF comparison \A_30120625003267.TXT,C:\Documents and Settings\aa24800\My Documents \PDFcomparison\B_30120502002776.TXT,Array (报价ID:,报价摘要:,报价日期:,跟踪ID(A):跟踪ID(Z):跟踪ID:)
不同应该能够返回结果 - 差异
Dim sRes:sRes = oDiffer.diffs()
'检查实际与预期结果
Dim sExp:sExp = goFS.OpenTextFile(预期)。ReadAll()
WScript.Echo--------- Res
WScript.Echo sRes
如果sExp = sRes则
WScript.Echo ok
'save result
goFS.CreateTextFile(C:\Documents and Settings\aa24800\My Documents \PDF comparison\Result.TXT,True).Write sRes
TrialVersion = 0 Else
'show failure
WScript.Echo--------- Exp
WScript.Echo sExp
WScript.Echonot ok
TrialVersion = 1
结束如果
结束函数'TrialVersion
'trivial Differ
'类cDiffer
Dim m_sLFSpec:m_sLFSpec =C: \\文件和设置\aa24800 \My Documents \PDF比较\A_30120625003267.TXT
Dim m_sRFSpec:m_sRFSpec =C:\Documents和Settings\aa24800 \My Documents \PDF comparison \\ \\ B_30120502002776.TXT
'constructorwith params
公共函数init(sLFSpec,sRFSpec)
设置init = Me
m_sLFSpec = sLFSpec
m_sRFSpec = sRFSpec
End Function
公共函数diffs()
diffs =cDiffer.diffs()尚未实现。
结束函数'diffs
'结束类'cDiffer00
'gold Differ
'类cDiffer
'私有m_sLFSpec'文件规格
'私有m_sRF规格
私有m_sLFiNa文件名
私有m_sRFiNa
私有m_dicLabels'存储和有效地找到选择性标签
'constructorparams
公共函数init(sLFSpec,sRFSpec,aLabels)
设置init = Me
m_sLFSpec = sLFSpec
m_sRFSpec = sRFSpec
m_sLFiNa = goFS.GetBaseName(sLFSpec)
m_sRFiNa = goFS.GetBaseName(sRFSpec)
设置m_dicLabels = CreateObject(Scripting.Dictionary)
m_dicLabels.CompareMode = vbTextCompare'不区分大小写
Dim sKey
对于每个sKey在aLabels
m_dicLabels(sKey)= 0
Next
结束函数
公共函数diffs()'使用ArrayList收集结果
Dim alRes:Set alRes = CreateObject(System.Collections.ArrayList)
'requested title
alRes.Add区别:
'打开两个输入文件
Dim tsL:Set tsL = goFS.OpenTextFile(m_sLFSpec)
Dim tsR:Set tsR = goFS .OpenTextFile(m_sRFSpec)
'在线路上循环
Do Until tsL.AtEndOfStream
Dim sLL:sLL = tsL.ReadLine()
Dim sRL
'第二个文件更短
如果tsR.AtEndOfStream则
alRes.AddtsR.AtEndOfStream
退出Do
否则
sRL = tsR.ReadLine()
结束如果
'如果线等于则不需要工作
如果sLL<> sRL then
如果m_dicLabels.Exists(Split(sLL,:)(0))then
Dim sLiNo:sLiNo = CStr(tsL.Line - 1)& :
alRes.Add Join(Array(m_sLFiNa,Line,sLiNo,sLL))
alRes.Add Join(Array(m_sRFiNa,Line,sLiNo,sRL))
End If
End If
Loop
tsL.Close
tsR.Close
diffs = Join(alRes.ToArray(),vbCrLf)& vbCrLf
结束函数'diffs
结束类'cDiffer

功能GoldVersion()
'不同应该知道要比较的文件
'和信息标签以选择
Dim oDiffer:Set oDiffer = New cDiffer.init(C:\Documents and Settings\aa24800\My Documents \PDF comparison \A_30120625003267.TXT,C:\文档和设置\aa24800 \My Documents \PDF比较\B_30120502002776.TXT,数组(报价ID:,报价摘要:,报价日期:,跟踪ID ,Tracking ID(Z):,Tracking ID:)
'不同应该能够返回结果 - 差异
Dim sRes:sRes = oDiffer.diffs()
'检查实际与预期结果
Dim sExp:sExp = goFS.OpenTextFile(Expected)。ReadAll()
WScript.Echo--------- Res
WScript.Echo sRes
如果sExp = sRes那么
WScript.Echook
'保存结果
goFS.CreateTextFile(C:\Documents和Settings\ aa24800 \My Documents \PDF comparison \Result.TXT,True).Write sRes
GoldVersion = 0 Else
'show failure
WScript.Echo------ --- Exp
WScript.Echo sExp
WScript.Echonot ok
GoldVersion = 1
End If
End Function'GoldVersion


解决方案

如果你是VBScript的新手,



开始使用SelFileComp.vbs:

 'SelFileComp.vbs  - 选择性文件比较

选项显式

Dim goFS:设置goFS = CreateObject(Scripting.FileSystemObject )

WScript.Quit TinVersion()

功能TinVersion()
WScript.Echo无法比较文件。
TinVersion = 1
结束函数'TinVersion

到某个合适的目录。添加输入和预期结果文件。
启动SelFileComp.vbs:

  cscript SelFileComp.vbs 
无法比较文件。
echo%ErrorLevel%
1

添加(并调用)TrialVersion准备和使用一个(微不足道的)Differ对象
在一个适合于健全的框架中执行重载:

 'SelFileComp.vbs  - 选择性文件比较

选项显式

Dim goFS:设置goFS = CreateObject(Scripting.FileSystemObject)

WScript.Quit TrialVersion()
WScript.Quit TinVersion()

功能TinVersion()
WScript.Echo无法比较文件。
TinVersion = 1
结束函数'TinVersion

函数TrialVersion()
'不同应该知道要比较的文件
'我们会担心关于后面的选择
Dim oDiffer:Set oDiffer = New cDiffer.init(_
File-1,File-2_

'能够返回结果 - 差异
Dim sRes:sRes = oDiffer.diffs()
'检查实际与预期结果
Dim sExp:sExp = goFS.OpenTextFile(Expected) .ReadAll()
WScript.Echo--------- Res
WScript.Echo sRes
如果sExp = sRes则
WScript.Echook
'保存结果
goFS.CreateTextFile(.. \data\Result,True).Write sRes
TrialVersion = 0
Else
'show failure
WScript.Echo--------- Exp
WScript.Echo sExp
WScript.Echonot ok
TrialVersion = 1
结束如果
结束函数'TrialVersion

'trivial不同
类cDiffer
私有m_sLFSpec
私有m_sRFSpec
构造函数带参数
public function init(sLFSpec,sRFSpec)
设置init = Me
m_sLFSpec = sLFSpec
m_sRFSpec = sRFSpec
结束函数
公共函数diffs()
diffs =cDiffer.diffs()尚未实现。
结束函数'diffs
结束类'cDiffer00

输出:

  cscript SelFileComp.vbs 
--------- Res
cDiffer.diffs然而。
--------- Exp
区别:
File-1第4行:价格3:$ 1234.00
文件2第4行:价格3:$ 5678.00
File-1第7行:期限:2年
File-2第7行:期限:3年

不确定

echo%ErrorLevel%
1

如果您随后重命名琐碎的cDiffer

 'trivial Differ 
Class cDiffer00

您可以重复使用名称(和TrialVersion()中的代码)得出一个至少进行一些比较的
cDiffer:

 '简单Differ 
类cDiffer
私有m_sLFSpec
私有m_sRFSpec
构造函数与参数
公共函数init ,sRFSpec)
设置init = Me
m_sLFSpec = sLFSpec
m_sRFSpec = sRFSpec
结束函数
公共函数diffs()
'使用ArrayList收集结果
Dim alRes:Set alRes = CreateObject(System.Collections.ArrayList)
'请求标题
alRes.Add区别:
'打开两个输入文件
Dim tsL:Set tsL = goFS.OpenTextFile(m_sLFSpec)
Dim tsR:Set tsR = goFS.OpenTextFile(m_sRFSpec)
'通过行循环
Do Until tsL.AtEndOfStream
Dim sLL:sLL = tsL.ReadLine()
Dim sRL
第二个文件可以更短
如果tsR.AtEndOfStream然后
alRes.AddtsR.AtEndOfStream
退出Do
否则
sRL = tsR.ReadLine()
结束如果
'如果线等于则不需要工作
如果sLL<> sRL then
alRes.Add???& sLL
alRes.Add???& sRL
End If
Loop
tsL.Close
tsR.Close
diffs = Join(alRes.ToArray(),vbCrLf)
End Function'diffs
结束类'cDiffer00

输出:


$ b b

  cscript SelFileComp.vbs 
--------- Res
区别:
日期:00/11/1234 /订货号:1111
日期:11/00/6789和订单号:2222
价格3:$ 1234.00
价格3:$ 5678.00
订单号:1111
订单号:2222
???期限:2年
?期限:3年
?日期:00/11/1234
日期:11/00/6789
--------- Exp
区别:
File-1第4行:价格3:$ 1234.00
File-2第4行:价格3:$ 5678.00
File-1第7行:期限:2年
File-2第7行:期限:3年

不确定

这清楚地显示了仍然要完成的子任务:


  1. 选择相关差异

  2. 输出格式

乐观并添加和调用GoldVersion()

 功能GoldVersion()
'不同应该知道要比较的文件
'和信息标签选择
Dim oDiffer:Set oDiffer = New cDiffer.init(_
File-1,File-2_
,Array 价格3,期限)_

'不同应该能够返回结果 - 差异
Dim sRes:sRes = oDiffer.diffs()
'检查实际与预期结果
Dim sExp:sExp = goFS.OpenTextFile(Expected)。ReadAll()
WScript.Echo--------- Res
WScript.Echo sRes
如果sExp = sRes那么
WScript.Echook
'保存结果
goFS.CreateTextFile(.. \data\Result, True).Write sRes
GoldVersion = 0
否则
'显示失败
WScript.Echo--------- Exp
WScript.Echo sExp
WScript.Echonot ok
GoldVersion = 1
End If
End Function'GoldVersion

有更好的cDiffer:

 'gold Differ 
Class cDiffer
私有m_sLFSpec'文件规范
私有m_sRFSpec
私有m_sLFiNa文件名
私有m_sRFiNa
私有m_dicLabels'存储并高效地找到选择性标签
'构造函数with params
公共函数init(sLFSpec,sRFSpec,aLabels)
设置init = Me
m_sLFSpec = sLFSpec
m_sRFSpec = sRFSpec
m_sLFiNa = goFS.GetBaseName )
m_sRFiNa = goFS.GetBaseName(sRFSpec)
设置m_dicLabels = CreateObject(Scripting.Dictionary)
m_dicLabels.CompareMode = vbTextCompare'不区分大小写
Dim sKey
对于每个sKey在aLabels
m_dicLabels(sKey)= 0
下一个
结束函数
公共函数diffs()
'使用ArrayList收集结果
Dim alRes:Set alRes = CreateObject(System.Collections.ArrayList)
'请求标题
alRes.Add区别:
'打开两个输入文件
Dim tsL :set tsL = goFS.OpenTextFile(m_sLFSpec)
Dim tsR:设置tsR = goFS.OpenTextFile(m_sRFSpec)
'通过行循环
Do Until tsL.AtEndOfStream
Dim sLL: sLL = tsL.ReadLine()
Dim sRL
第二个文件可以更短
如果tsR.AtEndOfStream然后
alRes.AddtsR.AtEndOfStream
退出
否则
sRL = tsR.ReadLine()
结束如果
'如果线等于则不需要工作
如果sLL<> sRL then
如果m_dicLabels.Exists(Split(sLL,:)(0))然后
alRes.Add Join(Array(m_sLFiNa,Line,sLL))
alRes。添加连接(数组(m_​​sRFiNa,Line,sRL))
结束如果
结束如果
循环
tsL.Close
tsR.Close
diffs = Join(alRes.ToArray(),vbCrLf)
结束函数'diffs
结束类'cDiffer


b $ b

输出:

  cscript SelFileComp.vbs 
--------- Res
区别:
文件-1行价格3:$ 1234.00
文件-2行价格3:$ 5678.00
文件1行期限:2年
File-2线路期限:3年
--------- Exp
区别:
文件-1第4行:价格3:$ 1234.00
文件2第4行:价格3:$ 5678.00
File-1第7行:期限:2年
File-2第7行:期限:3年

不确定

选择完成,格式化仍然不好。要提高输出:

 如果sLL<> sRL然后
如果m_dicLabels.Exists(Split(sLL,:)(0))然后
'alRes.Add Join(Array(m_sLFiNa,Line,sLL))
' alRes.Add Join(Array(m_sRFiNa,Line,sRL))
Dim sLiNo:sLiNo = CStr(tsL.Line - 1)& :
alRes.Add Join(Array(m_sLFiNa,Line,sLiNo,sLL))
alRes.Add Join(Array(m_sRFiNa,Line,sLiNo,sRL))
结束如果
结束如果

要添加结尾的vbCrLf:

 'diffs = Join(alRes.ToArray(),vbCrLf)
diffs = Join(alRes.ToArray(),vbCrLf)& vbCrLf

最终输出:

  cscript SelFileComp.vbs 
--------- Res
区别:
文件-1第4行:价格3:$ 1234.00
文件-2第4行:价格3:$ 5678.00
文件-1第7行:期限:2年
文件2第7行:期限:3年

ok

echo%ErrorLevel%
0

/ p>

更新A(wrt档案规格/档案名称)



移动/ -1至..\data\,更改

  Dim oDiffer:Set oDiffer = New cDiffer.init(_ 
File-1,File-2_
,Array(Price 3,Term)_

  Dim oDiffer:Set oDiffer = New cDiffer.init (_ 
.. \data\File-1,File-2_
,Array(Price 3,Term)_

结果将是相同的,因为cDiffer使用

  m_sLFSpec = sLFSpec 
存储(完整)路径
m_sLFiNa = goFS.GetBaseName(sLFSpec)
提取输出格式化的文件名
Dim tsL:设置tsL = goFS.OpenTextFile(m_sLFSpec)
打开文件

更新B(wrt字典)



A 字典是一个集合,存储在唯一键下的元素(作为
与数组相反,这使得它的项目可以通过数字访问)。通过
使用标签来查找字典的键,diffs()
函数可以有效地检查(看看没有循环!)检查,
行的第一部分是否up

 拆分(sLL,:)(0)
pre>

包含在字典中

 如果m_dicLabels.Exists Split(sLL,:)(0))然后

/ constructors)



类是一组(一组相似的)对象的定义/规范,它是一个
变量/组合数据(成员)和功能(方法)。 cDiffer是一个定义对象的类,它知道所有要比较的文件和要查找的标签(成员变量,如m_sLSpec),并可以'do'比较(方法/函数,如diffs())。 New语句用于根据规范构造/创建对象:

  Dim oDiffer:Set oDiffer = New cDiffer 

由New创建的对象为空,对实际目的无效;你可以
实现一个Class_Initialize()Sub(在Class ... End Class块中),但是
代码将用于类的所有对象,



如果您查看文档中的 Class 语句,你将
意识到,无参数的constructor(Class_Initialize)是
对于没有按线/小时支付的程序员来说没什么用。锅炉板
代码

  Private Sub Class_Initialize 
m_CustomerName =
m_OrderCount = 0
... ad nauseam:将所有其他成员数据设置为nix
End Sub


$ b b

特别令人厌恶,因为VBScript




  • 在调用New时自动执行一个空Class_Initialize等效于

  • 将所有变量初始化为自动清空,并清空

    对字符串和数字起作用。



补救措施是忘记Class_Initialize(除了特殊情况)和
在一个或多个方面投入一些努力

  public function initXXX(p1,p2,... pn)
设置initXXX = Me'返回VBScript的调用者
...使用p1 ... pn初始化成员数据值
结束函数


First of all, I am not from programming background and totally new to VBscript. For some reasons, I have to do a this scripting task at office. I want to use it with Quick Test Professional 11.

I have gone through many posts here as well on other forums but not able to find the required information.

Ok so here's what I need to do:

I have to compare two text files and write the difference in third file. Both the files have almost same content aprt from some field, ie: Date, Order no and so on.

For example, File-1 has Date: 00/11/1234 and Order no: 1111 and File-2 has Date: 11/00/6789 and Order no: 2222 So is there any way that I can ignore these fields and its value? Is there any way that I can create ignore list which I can add and which will be used during comparison and will skip the fields during comparison? So my difference file will not have these difference as these values will always be different. And so I can get the all other differences in my result file.

For your reference, here is the sample files.

So far I have compared both the files but in a simplest way, I don't know how to ignore the fields. I want to make these task as a function so that I can use it in my function library.

File-1

Date: 00/11/1234 / Order no: 1111

Price 1: $1111.00

Price 2: $2222.00

Price 3: $1234.00

ABC def GHI kjl 1111

Order no: 1111

Term: 2-Year

Date: 00/11/1234

File-2

Date: 11/00/6789 and Order no: 2222

Price 1: $1111.00

Price 2: $2222.00

Price 3: $5678.00

ABC def GHI kjl 1111

Order no: 2222

Term: 3-Year

Date: 11/00/6789

Result file should display:

Differences:

File-1 Line 4: Price 3: $1234.00

File-2 Line 4: Price 3: $5678.00

File-1 Line 7: Term: 2-Year

File-2 Line 7: Term: 3-Year

Thank you very much in advance.

Hi @Ekkehard.Horner Thank a lot for your help and time and for tolerating my sily questions. The fact is, the more I tried to understand your code, the more I got confused. When I put this below code in Quick Test Pro_11, it throws me syntax error @ "Dim oDiffer : Set oDiffer = New cDiffer.init("C:......" QTP is saying "Expected End of STatement" between "... New cDiffer" and ".init" QTP showed me error in both function "TrailVersion" as well as in function "GoldVersion"

It will be more than great if you will throw some light on this. And is it necessary to have "Expected" text file...? As I dont want to include that part because otherwise I've to create "Expected" file for my every comparison.

Please pardon me my sily questions.

Thanks in advance.

Class cDiffer   
Option Explicit  
Dim goFS : Set goFS = CreateObject("Scripting.FileSystemObject")  
    WScript.Quit TrialVersion() 
    WScript.Quit TinVersion()  
Function TinVersion()   
    WScript.Echo "can't compare files yet."   
    TinVersion = 1 
End Function ' TinVersion  
HERE I'VE COMMENTED TRIALVERSION FUNCTION 
Function TrialVersion()   
Dim oDiffer : Set oDiffer = New cDiffer.init("C:\Documents and Settings\24800\My Documents\PDF comparison\A_30120625003267.TXT", "C:\Documents and Settings\aa24800\My Documents\PDFcomparison\B_30120502002776.TXT", Array("Quote ID:", "Quote Summary for:", "Quote Date:", "Tracking ID (A):", "Tracking ID (Z):", "Tracking ID:")
    ' the differ should be able to return a result - the differences   
    Dim sRes : sRes = oDiffer.diffs()   
    ' check actual vs. expected result   
    Dim sExp : sExp = goFS.OpenTextFile("Expected").ReadAll()  
    WScript.Echo "--------- Res"   
    WScript.Echo sRes   
    If sExp = sRes Then      
        WScript.Echo "ok"      
        ' save result      
        goFS.CreateTextFile("C:\Documents and Settings\aa24800\My Documents\PDF comparison\Result.TXT", True).Write sRes      
        TrialVersion = 0   Else      
        ' show failure      
        WScript.Echo "--------- Exp"      
        WScript.Echo sExp      
        WScript.Echo "not ok"      
        TrialVersion = 1   
    End If 
End Function ' TrialVersion  
'trivial Differ 
'Class cDiffer   
    Dim m_sLFSpec : m_sLFSpec = "C:\Documents and Settings\aa24800\My Documents\PDF comparison\A_30120625003267.TXT"
Dim m_sRFSpec : m_sRFSpec = "C:\Documents and Settings\aa24800\My Documents\PDF comparison\B_30120502002776.TXT"   
    ' "constructor" with params   
    Public Function init(sLFSpec, sRFSpec)     
        Set init  = Me     
        m_sLFSpec = sLFSpec     
        m_sRFSpec = sRFSpec   
    End Function   
    Public Function diffs()     
        diffs = "cDiffer.diffs() not implemented yet."   
    End Function ' diffs 
'End Class ' cDiffer00
'gold Differ 
'Class cDiffer   
'   Private m_sLFSpec   ' file specs   
'   Private m_sRFSpec   
    Private m_sLFiNa    ' file names   
    Private m_sRFiNa   
    Private m_dicLabels ' store and efficiently find selective labels   
    ' "constructor" with params   
    Public Function init(sLFSpec, sRFSpec, aLabels)     
        Set init  = Me     
        m_sLFSpec = sLFSpec     
        m_sRFSpec = sRFSpec     
        m_sLFiNa  = goFS.GetBaseName(sLFSpec)     
        m_sRFiNa  = goFS.GetBaseName(sRFSpec)     
        Set m_dicLabels = CreateObject("Scripting.Dictionary")     
        m_dicLabels.CompareMode = vbTextCompare ' case-insensitive     
        Dim sKey     
        For Each sKey In aLabels         
            m_dicLabels(sKey) = 0     
        Next   
    End Function   
    Public Function diffs()     ' Use ArrayList to collect the results     
        Dim alRes : Set alRes = CreateObject("System.Collections.ArrayList")     
        ' requested title     
        alRes.Add "Differences:"     
        ' open both input files     
        Dim tsL   : Set tsL   = goFS.OpenTextFile(m_sLFSpec)     
        Dim tsR   : Set tsR   = goFS.OpenTextFile(m_sRFSpec)     
        ' loop over lines     
        Do Until tsL.AtEndOfStream        
            Dim sLL : sLL = tsL.ReadLine()        
            Dim sRL        
            ' second file could be shorter        
            If tsR.AtEndOfStream Then           
                alRes.Add "tsR.AtEndOfStream"           
        Exit Do        
            Else           
                sRL = tsR.ReadLine()        
            End If        
            ' no need for work if lines are equal        
            If sLL <> sRL Then           
                If m_dicLabels.Exists(Split(sLL, ":")(0))Then                  
                Dim sLiNo : sLiNo = CStr(tsL.Line - 1)& ":"              
            alRes.Add Join(Array(m_sLFiNa, "Line", sLiNo, sLL))              
            alRes.Add Join(Array(m_sRFiNa, "Line", sLiNo, sRL))           
            End If        
        End If     
    Loop     
    tsL.Close     
    tsR.Close     
    diffs = Join(alRes.ToArray(), vbCrLf) & vbCrLf   
End Function ' diffs 
End Class ' cDiffer

Function GoldVersion()   
   ' the differ should know about the files to compare   
   ' and the info labels to select   
   Dim oDiffer : Set oDiffer = New cDiffer.init("C:\Documents and Settings\aa24800\My Documents\PDF comparison\A_30120625003267.TXT", "C:\Documents and Settings\aa24800\My Documents\PDF comparison\B_30120502002776.TXT", Array("Quote ID:", "Quote Summary for:", "Quote Date:", "Tracking ID (A):", "Tracking ID (Z):", "Tracking ID:")
   ' the differ should be able to return a result - the differences    
   Dim sRes : sRes = oDiffer.diffs()   
   ' check actual vs. expected result   
   Dim sExp : sExp = goFS.OpenTextFile("Expected").ReadAll()   
   WScript.Echo "--------- Res"   
   WScript.Echo sRes   
    If sExp = sRes Then      
       WScript.Echo "ok"      
       ' save result      
       goFS.CreateTextFile("C:\Documents and Settings\aa24800\My Documents\PDF comparison\Result.TXT", True).Write sRes      
       GoldVersion = 0   Else      
       ' show failure      
       WScript.Echo "--------- Exp"      
       WScript.Echo sExp      
       WScript.Echo "not ok"      
       GoldVersion = 1   
    End If 
End Function ' GoldVersion

解决方案

If you are new to VBScript, you may profit from tackling your current problem in a way that will help you with your next problem.

Start with putting SelFileComp.vbs:

'' SelFileComp.vbs - selective file compare

Option Explicit

Dim goFS : Set goFS = CreateObject("Scripting.FileSystemObject")

WScript.Quit TinVersion()

Function TinVersion()
  WScript.Echo "can't compare files yet."
  TinVersion = 1
End Function ' TinVersion

into some suitable directory. Add your input and expected result files. Start SelFileComp.vbs:

cscript SelFileComp.vbs
can't compare files yet.
echo %ErrorLevel%
1

Add (and call) a TrialVersion that prepares and uses a (trivial) Differ object to do the heavy lifting in a skeleton suitable to sanity check the implementation:

'' SelFileComp.vbs - selective file compare

Option Explicit

Dim goFS : Set goFS = CreateObject("Scripting.FileSystemObject")

WScript.Quit TrialVersion()
WScript.Quit TinVersion()

Function TinVersion()
  WScript.Echo "can't compare files yet."
  TinVersion = 1
End Function ' TinVersion

Function TrialVersion()
  ' the differ should know about the files to compare
  ' we'll worry about the selection later
  Dim oDiffer : Set oDiffer = New cDiffer.init( _
     "File-1", "File-2" _
  )
  ' the differ should be able to return a result - the differences
  Dim sRes : sRes = oDiffer.diffs()
  ' check actual vs. expected result
  Dim sExp : sExp = goFS.OpenTextFile("Expected").ReadAll()
  WScript.Echo "--------- Res"
  WScript.Echo sRes
  If sExp = sRes Then
     WScript.Echo "ok"
     ' save result
     goFS.CreateTextFile("..\data\Result", True).Write sRes
     TrialVersion = 0
  Else
     ' show failure
     WScript.Echo "--------- Exp"
     WScript.Echo sExp
     WScript.Echo "not ok"
     TrialVersion = 1
  End If
End Function ' TrialVersion

' trivial Differ
Class cDiffer
  Private m_sLFSpec
  Private m_sRFSpec
  ' "constructor" with params
  Public Function init(sLFSpec, sRFSpec)
    Set init  = Me
    m_sLFSpec = sLFSpec
    m_sRFSpec = sRFSpec
  End Function
  Public Function diffs()
    diffs = "cDiffer.diffs() not implemented yet."
  End Function ' diffs
End Class ' cDiffer00

output:

cscript SelFileComp.vbs
--------- Res
cDiffer.diffs() not implemented yet.
--------- Exp
Differences:
File-1 Line 4: Price 3: $1234.00
File-2 Line 4: Price 3: $5678.00
File-1 Line 7: Term: 2-Year
File-2 Line 7: Term: 3-Year

not ok

echo %ErrorLevel%
1

If you then rename the trivial cDiffer

' trivial Differ
Class cDiffer00

you can re-use the name (and the code in TrialVersion()) to come up with a cDiffer that does at least some comparing:

' simple Differ
Class cDiffer
  Private m_sLFSpec
  Private m_sRFSpec
  ' "constructor" with params
  Public Function init(sLFSpec, sRFSpec)
    Set init  = Me
    m_sLFSpec = sLFSpec
    m_sRFSpec = sRFSpec
  End Function
  Public Function diffs()
    ' Use ArrayList to collect the results
    Dim alRes : Set alRes = CreateObject("System.Collections.ArrayList")
    ' requested title
    alRes.Add "Differences:"
    ' open both input files
    Dim tsL   : Set tsL   = goFS.OpenTextFile(m_sLFSpec)
    Dim tsR   : Set tsR   = goFS.OpenTextFile(m_sRFSpec)
    ' loop over lines
    Do Until tsL.AtEndOfStream
       Dim sLL : sLL = tsL.ReadLine()
       Dim sRL
       ' second file could be shorter
       If tsR.AtEndOfStream Then
          alRes.Add "tsR.AtEndOfStream"
          Exit Do
       Else
          sRL = tsR.ReadLine()
       End If
       ' no need for work if lines are equal
       If sLL <> sRL Then
          alRes.Add "??? " & sLL
          alRes.Add "??? " & sRL
       End If
    Loop
    tsL.Close
    tsR.Close
    diffs = Join(alRes.ToArray(), vbCrLf)
  End Function ' diffs
End Class ' cDiffer00

output:

cscript SelFileComp.vbs
--------- Res
Differences:
??? Date: 00/11/1234 / Order no: 1111
??? Date: 11/00/6789 and Order no: 2222
??? Price 3: $1234.00
??? Price 3: $5678.00
??? Order no: 1111
??? Order no: 2222
??? Term: 2-Year
??? Term: 3-Year
??? Date: 00/11/1234
??? Date: 11/00/6789
--------- Exp
Differences:
File-1 Line 4: Price 3: $1234.00
File-2 Line 4: Price 3: $5678.00
File-1 Line 7: Term: 2-Year
File-2 Line 7: Term: 3-Year

not ok

This shows clearly which sub tasks are still to be done:

  1. Selection of relevant differences
  2. Output formatting

Let's be optimistic and add and call GoldVersion()

Function GoldVersion()
  ' the differ should know about the files to compare
  ' and the info labels to select
  Dim oDiffer : Set oDiffer = New cDiffer.init( _
      "File-1", "File-2" _
    , Array("Price 3", "Term") _
  )
  ' the differ should be able to return a result - the differences
  Dim sRes : sRes = oDiffer.diffs()
  ' check actual vs. expected result
  Dim sExp : sExp = goFS.OpenTextFile("Expected").ReadAll()
  WScript.Echo "--------- Res"
  WScript.Echo sRes
  If sExp = sRes Then
     WScript.Echo "ok"
     ' save result
     goFS.CreateTextFile("..\data\Result", True).Write sRes
     GoldVersion = 0
  Else
     ' show failure
     WScript.Echo "--------- Exp"
     WScript.Echo sExp
     WScript.Echo "not ok"
     GoldVersion = 1
  End If
End Function ' GoldVersion

with a better cDiffer:

' gold Differ
Class cDiffer
  Private m_sLFSpec   ' file specs
  Private m_sRFSpec
  Private m_sLFiNa    ' file names
  Private m_sRFiNa
  Private m_dicLabels ' store and efficiently find selective labels
  ' "constructor" with params
  Public Function init(sLFSpec, sRFSpec, aLabels)
    Set init  = Me
    m_sLFSpec = sLFSpec
    m_sRFSpec = sRFSpec
    m_sLFiNa  = goFS.GetBaseName(sLFSpec)
    m_sRFiNa  = goFS.GetBaseName(sRFSpec)
    Set m_dicLabels = CreateObject("Scripting.Dictionary")
    m_dicLabels.CompareMode = vbTextCompare ' case-insensitive
    Dim sKey
    For Each sKey In aLabels
        m_dicLabels(sKey) = 0
    Next
  End Function
  Public Function diffs()
    ' Use ArrayList to collect the results
    Dim alRes : Set alRes = CreateObject("System.Collections.ArrayList")
    ' requested title
    alRes.Add "Differences:"
    ' open both input files
    Dim tsL   : Set tsL   = goFS.OpenTextFile(m_sLFSpec)
    Dim tsR   : Set tsR   = goFS.OpenTextFile(m_sRFSpec)
    ' loop over lines
    Do Until tsL.AtEndOfStream
       Dim sLL : sLL = tsL.ReadLine()
       Dim sRL
       ' second file could be shorter
       If tsR.AtEndOfStream Then
          alRes.Add "tsR.AtEndOfStream"
          Exit Do
       Else
          sRL = tsR.ReadLine()
       End If
       ' no need for work if lines are equal
       If sLL <> sRL Then
          If m_dicLabels.Exists(Split(sLL, ":")(0)) Then
             alRes.Add Join(Array(m_sLFiNa, "Line", sLL))
             alRes.Add Join(Array(m_sRFiNa, "Line", sRL))
          End If
       End If
    Loop
    tsL.Close
    tsR.Close
    diffs = Join(alRes.ToArray(), vbCrLf)
  End Function ' diffs
End Class ' cDiffer

output:

cscript SelFileComp.vbs
--------- Res
Differences:
File-1 Line Price 3: $1234.00
File-2 Line Price 3: $5678.00
File-1 Line Term: 2-Year
File-2 Line Term: 3-Year
--------- Exp
Differences:
File-1 Line 4: Price 3: $1234.00
File-2 Line 4: Price 3: $5678.00
File-1 Line 7: Term: 2-Year
File-2 Line 7: Term: 3-Year

not ok

Selection done, formatting still not good. To improve the output:

       If sLL <> sRL Then
          If m_dicLabels.Exists(Split(sLL, ":")(0)) Then
'            alRes.Add Join(Array(m_sLFiNa, "Line", sLL))
'            alRes.Add Join(Array(m_sRFiNa, "Line", sRL))
             Dim sLiNo : sLiNo = CStr(tsL.Line - 1) & ":"
             alRes.Add Join(Array(m_sLFiNa, "Line", sLiNo, sLL))
             alRes.Add Join(Array(m_sRFiNa, "Line", sLiNo, sRL))
          End If
       End If

To add the trailing vbCrLf:

'   diffs = Join(alRes.ToArray(), vbCrLf)
    diffs = Join(alRes.ToArray(), vbCrLf) & vbCrLf

Final output:

cscript SelFileComp.vbs
--------- Res
Differences:
File-1 Line 4: Price 3: $1234.00
File-2 Line 4: Price 3: $5678.00
File-1 Line 7: Term: 2-Year
File-2 Line 7: Term: 3-Year

ok

echo %ErrorLevel%
0

Next problem, please!

Update A (wrt file specs/file names)

Move/Copy File-1 to ..\data\, change

  Dim oDiffer : Set oDiffer = New cDiffer.init( _
      "File-1", "File-2" _
    , Array("Price 3", "Term") _
  )

to

  Dim oDiffer : Set oDiffer = New cDiffer.init( _
      "..\data\File-1", "File-2" _
    , Array("Price 3", "Term") _
  )

results will be the same, because cDiffer uses

m_sLFSpec = sLFSpec
  to store the (full) path
m_sLFiNa  = goFS.GetBaseName(sLFSpec)
  to extract the file name for output formatting
Dim tsL   : Set tsL   = goFS.OpenTextFile(m_sLFSpec)
  to open the file

Update B (wrt dictionary)

A dictionary is a collection that stores elements under unique keys (as opposed to an array, which makes its items accessible via numbers). By using the labels to look for as keys of a dictionary, the diffs() function can efficiently (look ma, no loops!) check, whether the first part of the line upto the :

  Split(sLL, ":")(0)

is contained in the dictionary

  If m_dicLabels.Exists(Split(sLL, ":")(0)) Then

Update C (wrt classes/constructors)

A class is the definition/specification of a (set of similar) object(s), that is a variable holding/combining data (members) and and functionality (methods). cDiffer is a class defining objects that 'know' all about the files to compare and the labels to look for (member variables like m_sLSpec) and can 'do' comparisons (methods/functions like diffs()). The New statement is used to construct/create objects according to specs:

  Dim oDiffer : Set oDiffer = New cDiffer

An object created by New is Empty, that is useless for practical purposes; you can implement a Class_Initialize() Sub (in the Class ... End Class block), but as that code would be used for all objects of the class, the gain is small.

If you look at the example in the Docs for the Class statement, you'll realize, that the parameter-less 'constructor' (Class_Initialize) is of little use to programmers who aren't paid by line/hour. The boiler plate code

   Private Sub Class_Initialize
      m_CustomerName = ""
      m_OrderCount = 0
      ... ad nauseam: set all other member data to 'nix'
   End Sub

is especially disgusting, because VBScript

  • executes the equivalent of an empty Class_Initialize automatically as soon as you call New
  • initializes all variables to Empty automatically and Empty will
    work fine for strings and numbers

The remedy is to forget Class_Initialize (except for special cases) and invest some effort in one or more

  Public Function initXXX(p1, p2, ... pn)
    Set initXXX = Me  ' return VBScript's this to caller
    ... use p1 ... pn to initialize member data to useful values
  End Function

这篇关于比较文本文件 - 使用VBscripting注销一些文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆