Skip to main content

让Python支持中文关键字和中文内置函数的生产力工具

Project description

# ChinesePython

让 Python 支持中文关键字和中文内置函数的生产力工具。

## 特性

- **中文关键字**`如果``否则``循环``对于``定义`- **中文内置函数**`打印()``输入()``长度()``整数()`- **完整覆盖**:35个关键字 + 71个内置函数
- **保护机制**:字符串内中文、注释、中文变量名全部保留
- **属性访问**`np.数组``np.array``pd.读取_csv``pd.read_csv`
- **零依赖**:纯标准库实现
- **Python 3.9+**:使用 AST 解析,稳定可靠

## 安装

```bash
pip install ChinesePython

快速开始

方式一:执行中文代码字符串

from ChinesePython import execute

code = '''
打印("你好,世界!")

定义 问候(名字):
    返回 "你好," + 名字

结果 = 问候("张三")
打印(结果)

如果 结果:
    打印("问候成功")
否则:
    打印("问候失败")
'''

execute(code)

输出:

你好,世界!
你好,张三
问候成功

方式二:执行中文代码文件

创建 hello.chpy 文件:

# hello.chpy
导入 os
导入 numpy 作为 np

打印("当前目录:", os.获取当前目录())

数据 = np.数组([1, 2, 3, 4, 5])
打印("数组长度:", 长度(数据))
打印("数组求和:", 求和(数据))

对于 i  范围(3):
    打印(f"循环第 {i} 次")

执行:

from ChinesePython import execute_file

execute_file("hello.chpy")

方式三:命令行运行

安装后可直接使用 chinpy 命令:

chinpy hello.chpy

方式四:转译为标准 Python

from ChinesePython import translate

cn_code = '''
如果 分数 >= 60:
    打印("及格")
否则:
    打印("不及格")
'''

py_code = translate(cn_code)
print(py_code)

输出:

if score >= 60:
    print("及格")
else:
    print("不及格")

方式五:交互式 REPL

from ChinesePython import repl

repl()

然后在 REPL 中直接输入中文代码:

>>> 打印("你好")
你好
>>> 定义 平方(x):
...     返回 x * x
...
>>> 打印(平方(5))
25
>>> 退出()

完整映射表

关键字 (35个)

中文 英文 中文 英文
如果 if 否则 else
否则如果 elif 循环 while
对于 for in
范围 range 继续 continue
跳出 break 定义 def
函数 def class
返回 return 生成 yield
匿名 lambda 无操作 pass
并且 and 或者 or
不是 not is
True False
None 尝试 try
捕获 except 最终 finally
抛出 raise from
导入 import 全局 global
非局部 nonlocal 异步 async
等待 await 释放 del
断言 assert 上下文 with
作为 as

内置函数 (71个)

中文 英文 中文 英文
打印 print 输入 input
整数 int 浮点数 float
复数 complex 字符串 str
字节 bytes 字节数组 bytearray
列表 list 元组 tuple
字典 dict 集合 set
冻结集合 frozenset 布尔 bool
二进制 bin 八进制 oct
十六进制 hex 绝对值 abs
四舍五入 round pow
求和 sum 最小值 min
最大值 max 除整取余 divmod
长度 len 枚举 enumerate
反转 reversed 排序 sorted
过滤 filter 映射 map
压缩 zip 切片 slice
任意 any 全部 all
类型 type 内存地址 id
哈希 hash 可调用 callable
实例 isinstance 子类 issubclass
设置属性 setattr 获取属性 getattr
判断属性 hasattr 删除属性 delattr
超类 super 对象 object
打开文件 open 执行 exec
计算 eval 编译 compile
全局变量 globals 局部变量 locals
迭代 iter 下一个 next
字符转整数 ord 整数转字符 chr
内存视图 memoryview 断点 breakpoint
帮助 help 格式化 format
属性 property 静态方法 staticmethod
类方法 classmethod repr repr
ascii ascii

支持第三方库

直接使用原英文名称,无需转换:

导入 os
导入 sys
导入 time
导入 pygame
导入 numpy 作为 np
导入 pandas 作为 pd
导入 torch
导入 tensorflow 作为 tf
 PyQt5 导入 QtWidgets
导入 tkinter 作为 tk

注意事项

  1. 变量名可以使用中文,不会触发替换
  2. 字符串内的中文 完全保留
  3. 注释内的中文 完全保留
  4. 遇到语法错误时会自动降级处理

开发计划

  • 支持 如果xxx: 的智能提示
  • 更多第三方库的中文别名预设
  • VS Code 插件支持

贡献

欢迎提交 Issue 和 Pull Request!

许可证

GPL License




```markdown
# ChinesePython

Write Python in Chinese. A productivity tool that enables Chinese keywords and Chinese built-in functions in Python.

## Features

- ✅ **Chinese Keywords**: `如果` (if), `否则` (else), `循环` (while), `对于` (for), `定义` (def), etc.
- ✅ **Chinese Built-in Functions**: `打印` (print), `输入` (input), `长度` (len), `整数` (int), etc.
- ✅ **Full Coverage**: All 35 Python keywords + 71 built-in functions
- ✅ **Safe Translation**: Strings, comments, and Chinese variable names are preserved
- ✅ **Attribute Access**: `np.数组` → `np.array`, `pd.读取_csv` → `pd.read_csv`
- ✅ **Zero Dependencies**: Pure standard library implementation
- ✅ **Python 3.9+**: AST-based parsing, stable and reliable

## Installation

```bash
pip install ChinesePython

Quick Start

Method 1: Execute Chinese Code String

from ChinesePython import execute

code = '''
打印("Hello, World!")

定义 greet(name):
    返回 "Hello, " + name

result = greet("Zhang San")
打印(result)

如果 result:
    打印("Greeting successful")
否则:
    打印("Greeting failed")
'''

execute(code)

Output:

Hello, World!
Hello, Zhang San
Greeting successful

Method 2: Execute Chinese Code File

Create hello.chpy:

# hello.chpy
导入 os
导入 numpy as np

打印("Current directory:", os.getcwd())

data = np.数组([1, 2, 3, 4, 5])
打印("Array length:", 长度(data))
打印("Array sum:", 求和(data))

对于 i in 范围(3):
    打印(f"Loop iteration {i}")

Execute:

from ChinesePython import execute_file

execute_file("hello.chpy")

Method 3: Command Line

After installation, use the chinpy command:

chinpy hello.chpy

Method 4: Translate to Standard Python

from ChinesePython import translate

cn_code = '''
如果 score >= 60:
    打印("Pass")
否则:
    打印("Fail")
'''

py_code = translate(cn_code)
print(py_code)

Output:

if score >= 60:
    print("Pass")
else:
    print("Fail")

Method 5: Interactive REPL

from ChinesePython import repl

repl()

Then type Chinese code directly:

>>> 打印("Hello")
Hello
>>> 定义 square(x):
...     返回 x * x
...
>>> 打印(square(5))
25
>>> exit()

Complete Mapping Tables

Keywords (35)

Chinese English Chinese English
如果 if 否则 else
否则如果 elif 循环 while
对于 for in
范围 range 继续 continue
跳出 break 定义 def
函数 def class
返回 return 生成 yield
匿名 lambda 无操作 pass
并且 and 或者 or
不是 not is
True False
None 尝试 try
捕获 except 最终 finally
抛出 raise from
导入 import 全局 global
非局部 nonlocal 异步 async
等待 await 释放 del
断言 assert 上下文 with
作为 as

Built-in Functions (71)

Chinese English Chinese English
打印 print 输入 input
整数 int 浮点数 float
复数 complex 字符串 str
字节 bytes 字节数组 bytearray
列表 list 元组 tuple
字典 dict 集合 set
冻结集合 frozenset 布尔 bool
二进制 bin 八进制 oct
十六进制 hex 绝对值 abs
四舍五入 round pow
求和 sum 最小值 min
最大值 max 除整取余 divmod
长度 len 枚举 enumerate
反转 reversed 排序 sorted
过滤 filter 映射 map
压缩 zip 切片 slice
任意 any 全部 all
类型 type 内存地址 id
哈希 hash 可调用 callable
实例 isinstance 子类 issubclass
设置属性 setattr 获取属性 getattr
判断属性 hasattr 删除属性 delattr
超类 super 对象 object
打开文件 open 执行 exec
计算 eval 编译 compile
全局变量 globals 局部变量 locals
迭代 iter 下一个 next
字符转整数 ord 整数转字符 chr
内存视图 memoryview 断点 breakpoint
帮助 help 格式化 format
属性 property 静态方法 staticmethod
类方法 classmethod repr repr
ascii ascii

Third-Party Library Support

Use original English names directly, no conversion needed:

导入 os
导入 sys
导入 time
导入 pygame
导入 numpy as np
导入 pandas as pd
导入 torch
导入 tensorflow as tf
from PyQt5 import QtWidgets
导入 tkinter as tk

Important Notes

  1. Chinese variable names are supported and will NOT be translated
  2. Strings containing Chinese are completely preserved
  3. Comments containing Chinese are completely preserved
  4. Automatic fallback handling for syntax errors

Roadmap

  • Smart提示 for 如果xxx:
  • Preset Chinese aliases for more third-party libraries
  • VS Code extension support

Contributing

Issues and Pull Requests are welcome!

License

GNU General Public License v3.0


---

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

cnzhpython-1.0.0.tar.gz (11.3 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

cnzhpython-1.0.0-py3-none-any.whl (12.3 kB view details)

Uploaded Python 3

File details

Details for the file cnzhpython-1.0.0.tar.gz.

File metadata

  • Download URL: cnzhpython-1.0.0.tar.gz
  • Upload date:
  • Size: 11.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.9.7

File hashes

Hashes for cnzhpython-1.0.0.tar.gz
Algorithm Hash digest
SHA256 c576a13e932e1be413e106acfef110a37acb3fbca6f605b56a665f8533f2a4e5
MD5 772ce30d365c6a91286a6a37214d61eb
BLAKE2b-256 ee438f7d86add73afa7661db40252610c725653bad28727ba55da8da705d7573

See more details on using hashes here.

File details

Details for the file cnzhpython-1.0.0-py3-none-any.whl.

File metadata

  • Download URL: cnzhpython-1.0.0-py3-none-any.whl
  • Upload date:
  • Size: 12.3 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.9.7

File hashes

Hashes for cnzhpython-1.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 1e02b8c9d512d9fabb73e94d507a8fceb821667e9e9a428e1a74b4e3644933a7
MD5 1251b5a220a5e185cede803e2c6317ce
BLAKE2b-256 d66f97d64f3da3cd6f304dc1ecb88408d89461923f6b867436c8a0351bd45fed

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page