Java - 从 PDF 文件中提取不重复的单词
Java - Extracting non duplicate words from PDF files
我在 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);
}
}
}
有没有办法提取不重复的单词?
- 将每行拆分为
space
- line.split(" ")
- 维护一个
HashSet
来保存这些词,并不断向其中添加所有词。
HashSet 本质上会忽略重复项。
HashSet<String> uniqueWords = new HashSet<>();
for (String line : lines) {
String[] words = line.split(" ");
for (String word : words) {
uniqueWords.add(word);
}
}
如果您的目标是删除重复项,那么实现它的一种方法是将数组添加到 java.util.Set
中。所以现在,您只需要做的是:
Set<String> noDuplicates = new HashSet<>( Arrays.asList( lines ) );
不再重复。
我在 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);
}
}
}
有没有办法提取不重复的单词?
- 将每行拆分为
space
-line.split(" ")
- 维护一个
HashSet
来保存这些词,并不断向其中添加所有词。
HashSet 本质上会忽略重复项。
HashSet<String> uniqueWords = new HashSet<>();
for (String line : lines) {
String[] words = line.split(" ");
for (String word : words) {
uniqueWords.add(word);
}
}
如果您的目标是删除重复项,那么实现它的一种方法是将数组添加到 java.util.Set
中。所以现在,您只需要做的是:
Set<String> noDuplicates = new HashSet<>( Arrays.asList( lines ) );
不再重复。