【发布时间】:2018-10-09 03:50:55
【问题描述】:
我用 Java 编写了一个简单的程序,使用 PDFBox 从 PDF 文件中提取单词。它从 PDF 中读取文本并逐字提取。
public class Main {
public static void main(String[] args) throws Exception {
try (PDDocument document = PDDocument.load(new File("C:\\my.pdf"))) {
if (!document.isEncrypted()) {
PDFTextStripper tStripper = new PDFTextStripper();
String pdfFileInText = tStripper.getText(document);
String lines[] = pdfFileInText.split("\\r?\\n");
for (String line : lines) {
System.out.println(line);
}
}
} catch (IOException e){
System.err.println("Exception while trying to read pdf document - " + e);
}
}
}
有没有办法提取不重复的单词?
【问题讨论】:
-
一般来说,您可以使用 Set
来实现这一点,如下所示: Set words = new HashSet ();然后你可以将每个单词添加到集合set.add(word)中,它会忽略重复的单词,之后你可以再次遍历集合来获取所有不重复的单词. -
@NoEm 在代码中看起来如何?
-
// 保存所有不重复的单词 Set
uniqueWords = new HashSet (); for (String line : lines) { String[] words = line.split(" "); for (String word : words) { uniqueWords.add(word.trim()); } } // 打印所有不重复的单词 System.out.println("Non-duplicated words: "); Iterator it = uniqueWords.iterator(); while(it.hasNext()){ System.out.println(it.next()); } -
您可以将其作为答案发布
标签: java pdfbox full-text-indexing