2017-07-18 41 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