ReMe/test/test6.py

15 lines
376 B
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import tiktoken
def count_tokens(text: str) -> int:
"""计算给定文本在指定模型下的 token 数量"""
encoding = tiktoken.get_encoding("o200k_base")
tokens = encoding.encode(text)
return len(tokens)
# 示例使用
text = "你好世界Hello, world!"
token_count = count_tokens(text)
print(f"Token 数量: {token_count}")
print(len(text) / 4)