Python 比较ruby中的两个文本文件
我有两个文本文件file1.txt和file2.txt。我想找出与文件的区别,该文件将突出显示相等、插入和删除文本。最终目标是创建一个html文件,该文件将以不同的颜色和样式突出显示文本(相等、插入和删除文本) file1.txtPython 比较ruby中的两个文本文件,python,ruby-on-rails,ruby,compare,readfile,Python,Ruby On Rails,Ruby,Compare,Readfile,我有两个文本文件file1.txt和file2.txt。我想找出与文件的区别,该文件将突出显示相等、插入和删除文本。最终目标是创建一个html文件,该文件将以不同的颜色和样式突出显示文本(相等、插入和删除文本) file1.txt I am testing this ruby code for printing the file diff. file2.txt I am testing this code for printing the file diff. 我正在使用这个代码 doc
I am testing this ruby code for printing the file diff.
file2.txt
I am testing this code for printing the file diff.
我正在使用这个代码
doc1 = File.open('file1.txt').read
doc2 = open('file2.txt').read
final_doc = Diffy::Diff.new(doc1, doc2).each_chunk.to_a
输出为:
-I am testing this ruby code for printing the file diff.
+I am testing this code for printing the file diff.
但是,我需要类似于以下格式的输出
equal:
I am testing this
insertion:
ruby
equal:
code for printing the file diff.
在python中有一个可以实现它的函数,但我在Ruby中没有发现这样的功能。我发现Ruby中有一些不同的库用于执行“diff”,但它们更侧重于逐行检查。我创建了一些代码,用于比较两个相对较短的字符串并显示它们之间的差异,这是一种快速的破解方法,如果在它们被删除的部分中突出显示被删除的部分不太重要的话,效果会很好。要做到这一点,只需要稍微考虑一下算法。但这段代码一次只能处理少量文本 与任何语言处理一样,关键在于正确地进行标记化。你不能一个字一个字地处理字符串。实际上,最好的方法是首先递归地循环,并将每个标记与文本中的某个位置关联起来,然后使用该位置进行分析,但下面的方法是快速而简单的
def self.change_differences(text1,text2) #oldtext, newtext
result = ""
tokens = text2.split(/(?<=[?.!,])/) #Positive look behind regexp.
for token in tokens
if text1.sub!(token,"") #Yes it contained it.
result += "<span class='diffsame'>" + token + "</span>"
else
result += "<span class='diffadd'>" + token + "</span>"
end
end
tokens = text1.split(/(?<=[?.!,])/) #Positive look behind regexp.
for token in tokens
result += "<span class='diffremove'>"+token+"</span>"
end
return result
end
def self.change_差异(text1,text2)#旧文本,新文本
result=“”
令牌=text2.split(/(?尝试使用此函数def difflib
。可能您可以将文本转换为数组。然后,array&array
是相等部分,array-array
是插入部分。为了查找文件之间的差异以及查找文件之间的共同点,您尝试过For Diffy吗?这似乎回答了您的问题对样式化HTML文件的原始请求,但您提供的输出示例是一个非常不同的请求。您可以使用git API: