2014-02-17 60 views
-1

我有这种方法接收作为参数pdfText(这是一个字符串,包含解析后的pdf文件中的文本)和fileName这是我想写的文本文件找到一个字符串,并返回它后面的文字

但是现在我需要在这个文本中找到单词“Keywords”,并且只提取它后面的单词,它们在同一行(直到换行符)。

比如我有一个地方包含以下行

标题一文:东西。

“关键词:计算机,机器人,当然”

标签:标签1,标签2,标签3。

结果应该是以下列表[“计算机”,“机器人”,“课程”]。

解决问题

所以我搜索如何解决我question..here是一个解决方案,不是很聪明,但它的工作原理:

  //index of first appearence of the word 
      int index = pdfText.indexOf("Keywords"); 

      //string from that to the end 
      String subStr = pdfText.substring(index); 


      //index of first appearence of the new line in the new string 
      int index1 = subStr.indexOf("\n"); 


      //the string we need 
      String theString = subStr.substring(9,index1); 

      System.out.println(theString); 

      //write in the file..use true as parameter for appending text,not overwrite it 
      FileWriter pw = new FileWriter(fileName,true); 
      pw.write(theString); 

      pw.close(); 
+4

请出示一些尝试!仅仅因为你发布了代码并不意味着你会努力解决你的问题。 –

+3

你可以通过让其他人做你的工作来获得A这个任务,但是你会在决赛中得到一个F。 –

+2

提示:研究'String#split()''String#startsWith()' –

回答

2

老实说,这个问题具体情况也是如此。不管:)

写入文件

String pdfText = "pdfText"; 
String fileLocation = "fileLocation"; 
Writer writer = null; 
try { 
    writer = new BufferedWriter(new OutputStreamWriter(
      new FileOutputStream(fileLocation), "utf-8")); 
    writer.write(pdfText);  // String you want to write (i.e. pdfText) 
} catch (IOException ioe) { 
    ioe.printStackTrace(); 
} finally { 
    try {writer.close();} catch (Exception ex) { ex.printStackTrace(); } 
} 

它总是一个好主意,指定编码类型。 ( “UTF-8”)。尽管你的任务可能并不重要。您可能还需要将追加到文件,而不是完全重写,在这种情况下,您应该为FileOutputStream使用不同的构造函数,new FileOutputStream(getFileLocation(), true)。至于很多try/catch块,不要效仿我的例子。这是我如何设法关闭我的资源,因为日食推荐哈哈。

解析字符串 如果你有一条线,如"Keywords : Computers, Robots, Course"

String str = "Keywords : Computers, Robots, Course"; 
String[] array = str.substring(indexOf(':') + 1).split(","); 
//this array = ["Computers", "Robots", "Course"] 

现在你有一个数组,可以遍历和写入/打印出来,但是你会喜欢。

1

你可以使用regex字后提取的话“关键词:”是这样的:

String regex = ".*Keywords\\s*:(.*)\\n.*"; 

String extractedLine = yourText.replaceAll(regex, "$1"); 

System.out.println(extractedLine); 
相关问题