2017-07-18 75 views
0

我有两个段落是有句子,我想比较两个段落,并希望显示UI的差异。文本比较算法或程序?

以下是可能的用例,我可以想一想。在算法或代码中的任何帮助将是可观的。

enter image description here

情况1:字删除从STR2

String str1 = "Hello I am new How are you"; 
String str2 = "How are you Hello"; 

output : 
str1 = "<del>Hello I am new</del> How are you"; 
str2 = "How are you <add>Hello</add>" 

情况2:字加入到STR2

String str1 = "Hello How are you what about you"; 
String str2 = "How are you I am fine what about you"; 

output : 
str1 = "<del>Hello</del> How are you what about you"; 
str2 = "How are you <add>I am fine</add> what about you" 

情况3:字相等

String str1 = "Hello How are you"; 
    String str2 = "Hello How rea you"; 

    output : 
    str1 = "Hello How <missmatch>are</missmatch> you"; 
    str2 = "Hello How <missmatch>rea</missmatch> you" 
+0

不应该在这两种情况下1和2包含第二个字符串而不是?如果将字符串'Hello'添加到'str2',它们将不相等。 –

+0

我不确定,但有一种算法用于删除插入等拼写校正,称为**对称删除拼写更正**。见http://blog.faroo.com/2012/06/07/improved-edit-distance-based-spelling-correction/你可能会有一些想法 –

+0

@NikolasCharalambidis在案例1和2中,子字符串已被添加新,这是在Str1中没有匹配 – user3676578

回答

1

你可以例如看看:https://github.com/wumpz/java-diff-utils和它的例子https://github.com/wumpz/java-diff-utils/wiki/Examples。包含特定标签而不是标记文字的修改很简单:例如,

DiffRowGenerator generator = DiffRowGenerator.create() 
       .showInlineDiffs(true) 
       .mergeOriginalRevised(true) 
       .inlineDiffByWord(true) 
       .newTag(f -> f?"<span style=\"background-color:#ffc6c6\">":"</span>") 
       .oldTag(f -> f?"<span style=\"background-color:#c4ffc3\">":"</span>") 
       .columnWidth(10000000) 
       .build(); 

List<DiffRow> rows = generator.generateDiffRows(
       Arrays.asList(lines.get(0)), 
       Arrays.asList(lines.get(1))); 

System.out.println(rows.get(0).getOldLine()); 
+0

您能否让我知道JAR及其Diff-utils的版本,因为我正在收到编译错误'方法create()未定义为类型DiffRowGenerator。“ – user3676578

+0

我从你的第一个链接中得到它,谢谢让我试试你的方法。 – user3676578

+0

你必须自己编译它。前谷歌java-diff-utils的其他版本位于maven central(我认为版本1.3.0)。但是这段代码在github上的版本库中为版本2.0-SNAPSHOT工作。谨防改变的groupid。 – wumpz