Classify text files and write to the index file

Classify each text file in a directory and write the results to the index file.

Documentation pages that include this code sample

To view the code sample used in context, see the following documentation:

Code sample

Python

def index(path, index_file):
    """Classify each text file in a directory and write
    the results to the index_file.
    """

    result = {}
    for filename in os.listdir(path):
        file_path = os.path.join(path, filename)

        if not os.path.isfile(file_path):
            continue

        try:
            with io.open(file_path, "r") as f:
                text = f.read()
                categories = classify(text, verbose=False)

                result[filename] = categories
        except Exception:
            print("Failed to process {}".format(file_path))

    with io.open(index_file, "w", encoding="utf-8") as f:
        f.write(json.dumps(result, ensure_ascii=False))

    print("Texts indexed in file: {}".format(index_file))
    return result

What's next

To search and filter code samples for other Google Cloud products, see the Google Cloud sample browser.