txtkit 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
txtkit-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 你的姓名
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
txtkit-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,77 @@
1
+ Metadata-Version: 2.4
2
+ Name: txtkit
3
+ Version: 0.1.0
4
+ Summary: 轻量中文文本处理小工具:字符统计、词频、清洗、按显示宽度截断
5
+ Author-email: reverend114 <reverend114@example.com>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/reverend114/txtkit
8
+ Project-URL: Source, https://github.com/reverend114/txtkit
9
+ Keywords: text,chinese,clean,word-frequency,文本处理
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Operating System :: OS Independent
12
+ Classifier: Natural Language :: Chinese (Simplified)
13
+ Classifier: Topic :: Text Processing
14
+ Classifier: Intended Audience :: Developers
15
+ Requires-Python: >=3.8
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ Dynamic: license-file
19
+
20
+ # txtkit
21
+
22
+ 轻量中文文本处理小工具,纯标准库实现,无第三方依赖。
23
+
24
+ ## 功能
25
+
26
+ | 函数 | 说明 |
27
+ | --- | --- |
28
+ | `count_chars(text)` | 统计汉字 / 字母 / 数字 / 空白 / 其他字符数量 |
29
+ | `word_freq(text, top=5, min_len=1)` | 统计词频,按次数降序 |
30
+ | `clean(text, lower, remove_punct, squeeze_space)` | 清洗文本:转小写、去标点、压缩空白 |
31
+ | `dedup_lines(text, keep_blank=False)` | 按行去重,保留首次出现顺序 |
32
+ | `text_width(text)` | 按显示宽度计算长度(全角算 2) |
33
+ | `truncate(text, width=20, suffix="…")` | 按显示宽度截断并加省略符 |
34
+
35
+ ## 安装
36
+
37
+ ```bash
38
+ pip install txtkit
39
+ ```
40
+
41
+ 从源码安装:
42
+
43
+ ```bash
44
+ pip install .
45
+ ```
46
+
47
+ ## 使用
48
+
49
+ ```python
50
+ from txtkit import count_chars, word_freq, clean, truncate
51
+
52
+ # 字符统计
53
+ print(count_chars("Python 很好用!2026"))
54
+ # {'total': 15, 'hanzi': 3, 'letters': 6, 'digits': 4, 'spaces': 1, 'others': 1}
55
+
56
+ # 词频
57
+ print(word_freq("我爱 Python 我爱 编程", top=2))
58
+ # [('我爱', 2), ('python', 1)]
59
+
60
+ # 清洗
61
+ print(clean(" 你 好 \t 世界 ! ", remove_punct=True))
62
+ # 你 好 世界
63
+
64
+ # 按显示宽度截断(列对齐时常需要)
65
+ print(truncate("中华人民共和国万岁", 10))
66
+ # 中华人民…
67
+ ```
68
+
69
+ ## 自测
70
+
71
+ ```bash
72
+ python tests/test_txttool.py
73
+ ```
74
+
75
+ ## 许可证
76
+
77
+ MIT License,详见 [LICENSE](LICENSE)。
txtkit-0.1.0/README.md ADDED
@@ -0,0 +1,58 @@
1
+ # txtkit
2
+
3
+ 轻量中文文本处理小工具,纯标准库实现,无第三方依赖。
4
+
5
+ ## 功能
6
+
7
+ | 函数 | 说明 |
8
+ | --- | --- |
9
+ | `count_chars(text)` | 统计汉字 / 字母 / 数字 / 空白 / 其他字符数量 |
10
+ | `word_freq(text, top=5, min_len=1)` | 统计词频,按次数降序 |
11
+ | `clean(text, lower, remove_punct, squeeze_space)` | 清洗文本:转小写、去标点、压缩空白 |
12
+ | `dedup_lines(text, keep_blank=False)` | 按行去重,保留首次出现顺序 |
13
+ | `text_width(text)` | 按显示宽度计算长度(全角算 2) |
14
+ | `truncate(text, width=20, suffix="…")` | 按显示宽度截断并加省略符 |
15
+
16
+ ## 安装
17
+
18
+ ```bash
19
+ pip install txtkit
20
+ ```
21
+
22
+ 从源码安装:
23
+
24
+ ```bash
25
+ pip install .
26
+ ```
27
+
28
+ ## 使用
29
+
30
+ ```python
31
+ from txtkit import count_chars, word_freq, clean, truncate
32
+
33
+ # 字符统计
34
+ print(count_chars("Python 很好用!2026"))
35
+ # {'total': 15, 'hanzi': 3, 'letters': 6, 'digits': 4, 'spaces': 1, 'others': 1}
36
+
37
+ # 词频
38
+ print(word_freq("我爱 Python 我爱 编程", top=2))
39
+ # [('我爱', 2), ('python', 1)]
40
+
41
+ # 清洗
42
+ print(clean(" 你 好 \t 世界 ! ", remove_punct=True))
43
+ # 你 好 世界
44
+
45
+ # 按显示宽度截断(列对齐时常需要)
46
+ print(truncate("中华人民共和国万岁", 10))
47
+ # 中华人民…
48
+ ```
49
+
50
+ ## 自测
51
+
52
+ ```bash
53
+ python tests/test_txttool.py
54
+ ```
55
+
56
+ ## 许可证
57
+
58
+ MIT License,详见 [LICENSE](LICENSE)。
@@ -0,0 +1,31 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77.0", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "txtkit"
7
+ version = "0.1.0"
8
+ description = "轻量中文文本处理小工具:字符统计、词频、清洗、按显示宽度截断"
9
+ readme = "README.md"
10
+ requires-python = ">=3.8"
11
+ license = "MIT"
12
+ license-files = ["LICENSE"]
13
+ authors = [
14
+ { name = "reverend114", email = "reverend114@example.com" },
15
+ ]
16
+ keywords = ["text", "chinese", "clean", "word-frequency", "文本处理"]
17
+ classifiers = [
18
+ "Programming Language :: Python :: 3",
19
+ "Operating System :: OS Independent",
20
+ "Natural Language :: Chinese (Simplified)",
21
+ "Topic :: Text Processing",
22
+ "Intended Audience :: Developers",
23
+ ]
24
+
25
+ [project.urls]
26
+ Homepage = "https://github.com/reverend114/txtkit"
27
+ Source = "https://github.com/reverend114/txtkit"
28
+
29
+ [tool.setuptools.packages.find]
30
+ include = ["txtkit*"]
31
+ namespaces = false
txtkit-0.1.0/setup.cfg ADDED
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,92 @@
1
+ """txtkit 自测脚本。
2
+
3
+ 不依赖 pytest,直接运行即可::
4
+
5
+ python tests/test_txttool.py
6
+
7
+ 安装后也可以用 pytest 跑::
8
+
9
+ python -m pytest tests -q
10
+ """
11
+
12
+ import os
13
+ import sys
14
+
15
+ # 未安装时也能从源码目录直接运行
16
+ sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
17
+
18
+ from txtkit import ( # noqa: E402
19
+ __version__,
20
+ clean,
21
+ count_chars,
22
+ dedup_lines,
23
+ text_width,
24
+ truncate,
25
+ word_freq,
26
+ )
27
+
28
+
29
+ def main():
30
+ print("txtkit %s 功能自测" % __version__)
31
+ print("=" * 46)
32
+
33
+ # 1. 字符统计
34
+ result = count_chars("Python 很好用!2026")
35
+ print("count_chars :", result)
36
+ assert result["hanzi"] == 3, result
37
+ assert result["letters"] == 6, result
38
+ assert result["digits"] == 4, result
39
+ assert result["spaces"] == 1, result
40
+ assert result["others"] == 1, result
41
+ print(" -> 通过")
42
+
43
+ # 2. 词频统计
44
+ freq = word_freq("我爱 Python 我爱 编程", top=3)
45
+ print("word_freq :", freq)
46
+ assert freq[0] == ("我爱", 2), freq
47
+ assert word_freq("python python Java")[0] == ("python", 2)
48
+ print(" -> 通过")
49
+
50
+ # 3. 文本清洗
51
+ cleaned = clean(" 你 好 \t 世界 ! ", remove_punct=True)
52
+ print("clean :", repr(cleaned))
53
+ assert cleaned == "你 好 世界", cleaned
54
+ assert clean(" 你 好 ") == "你 好"
55
+ assert clean("ABC", lower=True) == "abc"
56
+ print(" -> 通过")
57
+
58
+ # 4. 按行去重
59
+ deduped = dedup_lines("a\nb\na\n\nb")
60
+ print("dedup_lines :", repr(deduped))
61
+ assert deduped == "a\nb", deduped
62
+ print(" -> 通过")
63
+
64
+ # 5. 显示宽度截断
65
+ cut = truncate("中华人民共和国万岁", 10)
66
+ print("truncate :", repr(cut), "宽度 =", text_width(cut))
67
+ assert text_width(cut) <= 10, cut
68
+ assert truncate("短", 10) == "短"
69
+ print(" -> 通过")
70
+
71
+ # 6. 异常分支
72
+ for bad in (-1, 0):
73
+ try:
74
+ truncate("abc", bad)
75
+ except ValueError:
76
+ pass
77
+ else:
78
+ raise AssertionError("width=%r 应该抛 ValueError" % bad)
79
+ try:
80
+ count_chars(123)
81
+ except TypeError:
82
+ pass
83
+ else:
84
+ raise AssertionError("非字符串应抛 TypeError")
85
+ print("异常分支 : -> 通过")
86
+
87
+ print("=" * 46)
88
+ print("全部断言通过 ✅")
89
+
90
+
91
+ if __name__ == "__main__":
92
+ main()
@@ -0,0 +1,28 @@
1
+ """txtkit —— 轻量中文文本处理小工具。
2
+
3
+ 提供字符统计、词频统计、文本清洗、按显示宽度截断五个常用功能,
4
+ 纯标准库实现,无第三方依赖。
5
+
6
+ 示例::
7
+
8
+ >>> from txtkit import count_chars, truncate
9
+ >>> count_chars("Python 很好用!2026")["hanzi"]
10
+ 3
11
+ >>> truncate("中华人民共和国万岁", 10)
12
+ '中华人民…'
13
+ """
14
+
15
+ from .cleaner import clean, dedup_lines, text_width, truncate
16
+ from .counter import count_chars, word_freq
17
+
18
+ __version__ = "0.1.0"
19
+
20
+ __all__ = [
21
+ "count_chars",
22
+ "word_freq",
23
+ "clean",
24
+ "dedup_lines",
25
+ "text_width",
26
+ "truncate",
27
+ "__version__",
28
+ ]
@@ -0,0 +1,120 @@
1
+ """文本清洗、去重与按显示宽度截断。"""
2
+
3
+ import re
4
+ import unicodedata
5
+
6
+ # 半角空格、制表符、全角空格都压缩成一个半角空格
7
+ _SPACES = re.compile(r"[ \t\u3000]+")
8
+ # 标点:既不是字母数字下划线,也不是空白(汉字在 Python 3 里属于 \w)
9
+ _PUNCT = re.compile(r"[^\w\s]", re.UNICODE)
10
+
11
+
12
+ def clean(text, lower=False, remove_punct=False, squeeze_space=True):
13
+ """清洗文本:可选转小写、去标点、压缩连续空白,并去掉首尾空白。
14
+
15
+ 参数:
16
+ text: 待清洗的字符串
17
+ lower: 是否统一转成小写
18
+ remove_punct: 是否删除标点符号
19
+ squeeze_space:是否把连续空白压缩成一个空格
20
+
21
+ 返回:
22
+ 清洗后的字符串
23
+
24
+ 异常:
25
+ TypeError: text 不是字符串
26
+ """
27
+ if not isinstance(text, str):
28
+ raise TypeError("text 必须是 str,收到的是 %s" % type(text).__name__)
29
+
30
+ if lower:
31
+ text = text.lower()
32
+ if squeeze_space:
33
+ text = _SPACES.sub(" ", text)
34
+ if remove_punct:
35
+ text = _PUNCT.sub("", text)
36
+ return text.strip()
37
+
38
+
39
+ def dedup_lines(text, keep_blank=False):
40
+ """按行去重,保留首次出现的顺序。
41
+
42
+ 参数:
43
+ text: 多行字符串
44
+ keep_blank: 是否保留空行(默认不保留)
45
+
46
+ 返回:
47
+ 去重后的多行字符串
48
+
49
+ 异常:
50
+ TypeError: text 不是字符串
51
+ """
52
+ if not isinstance(text, str):
53
+ raise TypeError("text 必须是 str,收到的是 %s" % type(text).__name__)
54
+
55
+ seen = set()
56
+ result = []
57
+ for line in text.splitlines():
58
+ key = line.strip()
59
+ if not key and not keep_blank:
60
+ continue
61
+ if key in seen:
62
+ continue
63
+ seen.add(key)
64
+ result.append(key)
65
+ return "\n".join(result)
66
+
67
+
68
+ def text_width(text):
69
+ """按显示宽度计算长度:全角字符(汉字等)算 2,半角算 1。
70
+
71
+ 参数:
72
+ text: 待计算的字符串
73
+
74
+ 返回:
75
+ 显示宽度,int
76
+
77
+ 异常:
78
+ TypeError: text 不是字符串
79
+ """
80
+ if not isinstance(text, str):
81
+ raise TypeError("text 必须是 str,收到的是 %s" % type(text).__name__)
82
+ width = 0
83
+ for ch in text:
84
+ width += 2 if unicodedata.east_asian_width(ch) in ("W", "F") else 1
85
+ return width
86
+
87
+
88
+ def truncate(text, width=20, suffix="…"):
89
+ """按显示宽度截断字符串,超长时在末尾加上省略符。
90
+
91
+ 参数:
92
+ text: 待截断的字符串
93
+ width: 截断后的最大显示宽度(含省略符)
94
+ suffix: 省略符,默认 "…"
95
+
96
+ 返回:
97
+ 截断后的字符串;未超长时原样返回
98
+
99
+ 异常:
100
+ TypeError: text 不是字符串
101
+ ValueError: width 太小
102
+ """
103
+ if not isinstance(text, str):
104
+ raise TypeError("text 必须是 str,收到的是 %s" % type(text).__name__)
105
+ limit = width - text_width(suffix)
106
+ if limit <= 0:
107
+ raise ValueError("width 太小,容不下省略符")
108
+
109
+ if text_width(text) <= width:
110
+ return text
111
+
112
+ out = []
113
+ current = 0
114
+ for ch in text:
115
+ step = 2 if unicodedata.east_asian_width(ch) in ("W", "F") else 1
116
+ if current + step > limit:
117
+ break
118
+ out.append(ch)
119
+ current += step
120
+ return "".join(out) + suffix
@@ -0,0 +1,69 @@
1
+ """字符统计与词频统计。"""
2
+
3
+ import re
4
+ from collections import Counter
5
+
6
+ # 预编译正则,比每次调用 re.findall 的字符串模式更快
7
+ _HANZI = re.compile(r"[\u4e00-\u9fff]")
8
+ _LETTER = re.compile(r"[A-Za-z]")
9
+ _DIGIT = re.compile(r"[0-9]")
10
+ _SPACE = re.compile(r"\s")
11
+ # 一个"词"= 连续汉字 / 连续字母 / 连续数字
12
+ _WORD = re.compile(r"[\u4e00-\u9fff]+|[A-Za-z]+|[0-9]+")
13
+
14
+
15
+ def count_chars(text):
16
+ """统计文本中各类字符的数量。
17
+
18
+ 参数:
19
+ text: 待统计的字符串
20
+
21
+ 返回:
22
+ dict,键为 total / hanzi / letters / digits / spaces / others
23
+
24
+ 异常:
25
+ TypeError: text 不是字符串
26
+ """
27
+ if not isinstance(text, str):
28
+ raise TypeError("text 必须是 str,收到的是 %s" % type(text).__name__)
29
+
30
+ total = len(text)
31
+ hanzi = len(_HANZI.findall(text))
32
+ letters = len(_LETTER.findall(text))
33
+ digits = len(_DIGIT.findall(text))
34
+ spaces = len(_SPACE.findall(text))
35
+ return {
36
+ "total": total,
37
+ "hanzi": hanzi,
38
+ "letters": letters,
39
+ "digits": digits,
40
+ "spaces": spaces,
41
+ "others": total - hanzi - letters - digits - spaces,
42
+ }
43
+
44
+
45
+ def word_freq(text, top=5, min_len=1, ignore_case=True):
46
+ """统计词频,按出现次数降序返回前 top 个。
47
+
48
+ 参数:
49
+ text: 待统计的字符串
50
+ top: 返回多少条,必须为正整数
51
+ min_len: 词的最小长度,短于它的词会被忽略
52
+ ignore_case: 是否忽略大小写
53
+
54
+ 返回:
55
+ list[tuple[str, int]],例如 [('python', 2), ('java', 1)]
56
+
57
+ 异常:
58
+ TypeError: text 不是字符串
59
+ ValueError: top 不是正整数
60
+ """
61
+ if not isinstance(text, str):
62
+ raise TypeError("text 必须是 str,收到的是 %s" % type(text).__name__)
63
+ if not isinstance(top, int) or top <= 0:
64
+ raise ValueError("top 必须是正整数")
65
+
66
+ if ignore_case:
67
+ text = text.lower()
68
+ words = [w for w in _WORD.findall(text) if len(w) >= min_len]
69
+ return Counter(words).most_common(top)
@@ -0,0 +1,77 @@
1
+ Metadata-Version: 2.4
2
+ Name: txtkit
3
+ Version: 0.1.0
4
+ Summary: 轻量中文文本处理小工具:字符统计、词频、清洗、按显示宽度截断
5
+ Author-email: reverend114 <reverend114@example.com>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/reverend114/txtkit
8
+ Project-URL: Source, https://github.com/reverend114/txtkit
9
+ Keywords: text,chinese,clean,word-frequency,文本处理
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Operating System :: OS Independent
12
+ Classifier: Natural Language :: Chinese (Simplified)
13
+ Classifier: Topic :: Text Processing
14
+ Classifier: Intended Audience :: Developers
15
+ Requires-Python: >=3.8
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ Dynamic: license-file
19
+
20
+ # txtkit
21
+
22
+ 轻量中文文本处理小工具,纯标准库实现,无第三方依赖。
23
+
24
+ ## 功能
25
+
26
+ | 函数 | 说明 |
27
+ | --- | --- |
28
+ | `count_chars(text)` | 统计汉字 / 字母 / 数字 / 空白 / 其他字符数量 |
29
+ | `word_freq(text, top=5, min_len=1)` | 统计词频,按次数降序 |
30
+ | `clean(text, lower, remove_punct, squeeze_space)` | 清洗文本:转小写、去标点、压缩空白 |
31
+ | `dedup_lines(text, keep_blank=False)` | 按行去重,保留首次出现顺序 |
32
+ | `text_width(text)` | 按显示宽度计算长度(全角算 2) |
33
+ | `truncate(text, width=20, suffix="…")` | 按显示宽度截断并加省略符 |
34
+
35
+ ## 安装
36
+
37
+ ```bash
38
+ pip install txtkit
39
+ ```
40
+
41
+ 从源码安装:
42
+
43
+ ```bash
44
+ pip install .
45
+ ```
46
+
47
+ ## 使用
48
+
49
+ ```python
50
+ from txtkit import count_chars, word_freq, clean, truncate
51
+
52
+ # 字符统计
53
+ print(count_chars("Python 很好用!2026"))
54
+ # {'total': 15, 'hanzi': 3, 'letters': 6, 'digits': 4, 'spaces': 1, 'others': 1}
55
+
56
+ # 词频
57
+ print(word_freq("我爱 Python 我爱 编程", top=2))
58
+ # [('我爱', 2), ('python', 1)]
59
+
60
+ # 清洗
61
+ print(clean(" 你 好 \t 世界 ! ", remove_punct=True))
62
+ # 你 好 世界
63
+
64
+ # 按显示宽度截断(列对齐时常需要)
65
+ print(truncate("中华人民共和国万岁", 10))
66
+ # 中华人民…
67
+ ```
68
+
69
+ ## 自测
70
+
71
+ ```bash
72
+ python tests/test_txttool.py
73
+ ```
74
+
75
+ ## 许可证
76
+
77
+ MIT License,详见 [LICENSE](LICENSE)。
@@ -0,0 +1,11 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ tests/test_txttool.py
5
+ txtkit/__init__.py
6
+ txtkit/cleaner.py
7
+ txtkit/counter.py
8
+ txtkit.egg-info/PKG-INFO
9
+ txtkit.egg-info/SOURCES.txt
10
+ txtkit.egg-info/dependency_links.txt
11
+ txtkit.egg-info/top_level.txt
@@ -0,0 +1 @@
1
+ txtkit