clean_text.cc 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. // Copyright 2013 Google Inc. All Rights Reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. //
  15. // Author: jdtang@google.com (Jonathan Tang)
  16. //
  17. // Gets the cleantext of a page.
  18. #include <fstream>
  19. #include <iostream>
  20. #include <stdlib.h>
  21. #include <string>
  22. #include "gumbo.h"
  23. static std::string cleantext(GumboNode* node) {
  24. if (node->type == GUMBO_NODE_TEXT) {
  25. return std::string(node->v.text.text);
  26. } else if (node->type == GUMBO_NODE_ELEMENT &&
  27. node->v.element.tag != GUMBO_TAG_SCRIPT &&
  28. node->v.element.tag != GUMBO_TAG_STYLE) {
  29. std::string contents = "";
  30. GumboVector* children = &node->v.element.children;
  31. for (unsigned int i = 0; i < children->length; ++i) {
  32. const std::string text = cleantext((GumboNode*) children->data[i]);
  33. if (i != 0 && !text.empty()) {
  34. contents.append(" ");
  35. }
  36. contents.append(text);
  37. }
  38. return contents;
  39. } else {
  40. return "";
  41. }
  42. }
  43. int main(int argc, char** argv) {
  44. if (argc != 2) {
  45. std::cout << "Usage: clean_text <html filename>\n";
  46. exit(EXIT_FAILURE);
  47. }
  48. const char* filename = argv[1];
  49. std::ifstream in(filename, std::ios::in | std::ios::binary);
  50. if (!in) {
  51. std::cout << "File " << filename << " not found!\n";
  52. exit(EXIT_FAILURE);
  53. }
  54. std::string contents;
  55. in.seekg(0, std::ios::end);
  56. contents.resize(in.tellg());
  57. in.seekg(0, std::ios::beg);
  58. in.read(&contents[0], contents.size());
  59. in.close();
  60. GumboOutput* output = gumbo_parse(contents.c_str());
  61. std::cout << cleantext(output->root) << std::endl;
  62. gumbo_destroy_output(&kGumboDefaultOptions, output);
  63. }