2013-07-06 26 views
2

我有一堆關於Markdown格式編程的文本。有一個構建過程能夠將這些文本轉換爲Word/HTML,並執行簡單的驗證規則,如拼寫檢查或檢查文檔是否需要標題結構。我想擴展構建代碼以檢查所有文本中的複製粘貼或類似塊。檢測複製或類似的文本塊

是否有任何現有的Java/Groovy庫可以幫助我進行分析?

我的第一個想法是使用PMD的CopyPasteDetector,但是它過於強調分析實際代碼。我看不到我如何使用它來分析普通文本。

回答

1

畢竟我最終使用了CPD和Groovy。這裏是代碼,如果有人感興趣:

import net.sourceforge.pmd.cpd.Tokens 
import net.sourceforge.pmd.cpd.TokenEntry 
import net.sourceforge.pmd.cpd.Tokenizer 
import net.sourceforge.pmd.cpd.CPDNullListener 
import net.sourceforge.pmd.cpd.MatchAlgorithm 
import net.sourceforge.pmd.cpd.SourceCode 
import net.sourceforge.pmd.cpd.SourceCode.StringCodeLoader 
import net.sourceforge.pmd.cpd.SimpleRenderer 

// Prepare empty token data. 
TokenEntry.clearImages() 
def tokens = new Tokens() 

// List all source files with text. 
def source = new TreeMap<String, SourceCode>() 
new File('.').eachFile { file -> 
    if (file.isFile() && file.name.endsWith('.txt')) { 
    def analyzedText = file.text 
    def sourceCode = new SourceCode(new StringCodeLoader(analyzedText, file.name)) 
    source.put(sourceCode.fileName, sourceCode) 
    analyzedText.eachLine { line, lineNumber -> 
     line.split('[\\W\\s\\t\\f]+').each { token -> 
     token = token.trim() 
     if (token) { 
      tokens.add(new TokenEntry(token, sourceCode.fileName, lineNumber + 1)) 
     } 
     } 
    } 
    tokens.add(TokenEntry.getEOF()) 
    } 
} 

// Run matching algorithm. 
def maxTokenChain = 15 
def matchAlgorithm = new MatchAlgorithm(source, tokens, maxTokenChain, new CPDNullListener()) 
matchAlgorithm.findMatches() 

// Produce report. 
matchAlgorithm.matches().each { match -> 
    println " ========================================" 
    match.iterator().each { mark -> 
    println " DUPLICATION ERROR: <${mark.tokenSrcID}:${mark.beginLine}> [DUPLICATION] Found a ${match.lineCount} line (${match.tokenCount} tokens) duplication!" 
    } 
    def indentedTextSlice = "" 
    match.sourceCodeSlice.eachLine { line -> 
    indentedTextSlice += " $line\n" 
    } 
    println " ----------------------------------------" 
    println indentedTextSlice 
    println " ========================================" 
} 
2

你可能想嘗試Dude,我自己的快速和髒重複檢測器的文本文件。除了可以快速估計兩個文本文件之間的共享程度之外,還可以確定在一組文件之間進行復制,並繪製出一幅共享關係的良好圖表。