Skip to content

Instantly share code, notes, and snippets.

@r1cc4rd0m4zz4
Created September 18, 2024 21:36
Show Gist options
  • Select an option

  • Save r1cc4rd0m4zz4/c262ebcf0db6a7ab63da5ec7749d0b42 to your computer and use it in GitHub Desktop.

Select an option

Save r1cc4rd0m4zz4/c262ebcf0db6a7ab63da5ec7749d0b42 to your computer and use it in GitHub Desktop.
Calcola i token di un testo usando tiktoken
#!/usr/bin/env python3
## pip install tiktoken
import argparse
import tiktoken
import sys
def count_tokens(text, model_name="gpt-4"):
# Inizializza il tokenizzatore per il modello GPT-4
encoding = tiktoken.encoding_for_model(model_name)
tokens = encoding.encode(text)
return len(tokens)
def main():
parser = argparse.ArgumentParser(description="Calcola i token di un testo usando tiktoken.")
# Aggiunge un'opzione per l'input da file
parser.add_argument("txt_file", nargs='?', default=None, help="File di testo.")
# Analizza gli argomenti forniti
args = parser.parse_args()
if not args.txt_file:
text = sys.stdin.read()
else:
try:
with open(args.txt_file, 'r', encoding='utf-8') as file:
text = file.read()
except FileNotFoundError:
print(f"Errore: Il file {args.txt_file} non esiste.")
sys.exit(1)
# Conta i token
token_count = count_tokens(text)
print(f"{token_count}")
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment