【问题标题】:Google App Script find text from Google Document next to key text谷歌应用脚​​本从谷歌文档中查找关键文本旁边的文本
【发布时间】:2021-11-06 01:20:48
【问题描述】:

我有一个保存在 Google Drive 中的 PDF 文件,我想从该文件中找到一个文本,即 USD,然后选择找到的文本旁边的值,即:167.1764,并将其插入我的谷歌电子表格中。

以下是我的 PDF 文件的预览。 Link 到我的 PDF 文件。

这是我尝试但未能找到文本并达到其旁边的值的代码。

下面是我的代码。

function extractTextFromPDF() {

  var drive = DriveApp;
  var folders = drive.getFolderById('folderid');
  var newfile = folders.getFilesByName('08-Sep-2021.pdf');
  if(newfile.hasNext()){
    var file1 = newfile.next().getBlob();
  }
  
  var blob = file1;
  var resource = {
    title: blob.getName(),
    mimeType: blob.getContentType()
  };

  // Enable the Advanced Drive API Service
  var file = Drive.Files.insert(resource, blob, {ocr: true, ocrLanguage: "en"});

  // Extract Text from PDF file
  var doc = DocumentApp.openById(file.id);
  var text = doc.getBody().getText();
  Logger.log(text);
  //DriveApp.getFileById(file.id).setTrashed(true);
  var body = doc.getBody();
  var foundElement = body.findText("(USD)");

while (foundElement != null) {
    // Get the text object from the element
    var foundText = foundElement.getElement().asText();

    // Where in the element is the found text?
    var start = foundElement.getStartOffset();
    var end = foundElement.getEndOffsetInclusive();
}
    // i want the value of USD i.e 167.1144 in log
    Logger.log(foundText);
  
  
}

【问题讨论】:

  • 文件的格式总是一样的吗?您能分享实际的 PDF 进行测试吗?
  • 是的,格式相同,我已更新问题中的 PDF 文件链接。

标签: google-apps-script google-sheets automation google-drive-api google-docs-api


【解决方案1】:

RegEx 的帮助下,您可以提取它。我不是最好的那些模式。但也许其他人可以优化,因此不需要拆分。 (here 是一个链接)。

代码:

function extractTextFromPDF() {
  const folders = DriveApp.getFolderById('1QVo_pxxx387WPH9Yx');
  const newfile = folders.getFilesByName('08-Sep-2021.pdf');
  if(newfile.hasNext()){
    var file1 = newfile.next().getBlob();
  }
  
  const blob = file1;
  const resource = {
    title: blob.getName(),
    mimeType: blob.getContentType()
  };

  // Enable the Advanced Drive API Service
  const file = Drive.Files.insert(resource, blob, {convert: true});

  // Extract Text from PDF file
  const doc = DocumentApp.openById(file.id);
  const text = doc.getBody().getText();
  Logger.log(text);
  const buying = /USD\n(.*?)$/gm.exec(text)[1].trim();
  const selling = /USD\n\s*\S*\n(.*?)$/gm.exec(text)[1].trim();
  
  console.log(buying) 
  console.log(selling)

  //Remove the converted file.
  DriveApp.getFileById(file.id).setTrashed(true);

}

【讨论】:

  • 上面的脚本不工作,我也只需要买美元。
  • 那么你应该发布一个真正的pdf。我将您的屏幕截图保存为 pdf 并得到了您想要的结果..
  • 好的,我已经更新了问题中的 PDF 文件链接。
  • Super @RemcoE33:非常感谢,我想了解更多关于这个“RegEx”的信息。你能指导我去哪里吗?有视频教程吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多