PAYATHON 2026

如何在 Python 词频统计中拆分双连字符并保留单连字符和撇号?

数据小陈

结论

不要用 split() 切分后再靠 re.sub(r"^\W+|\W+$", "", word) 清理首尾标点,因为 token 内部的双连字符不会被处理。直接用正则匹配由字母组成、内部可带单个连字符或撇号的 token 更省事:

tokens = re.findall(r"[a-z]+(?:['-][a-z]+)*", text.lower())

don't、check-in 会保留,word--word 会匹配成两个 word。如果还要保留数字或 Unicode 字母,调整字符类即可。

原因

str.split() 只按空白切分,word--word 会被当成一个 token;re.sub(r"^\W+|\W+$", "", word) 只清理首尾非单词字符,不会动中间的 --。另外,\W 本身会匹配撇号和连字符,但这里的正则用 ^ 和 $ 限定了首尾,所以 don't、check-in 内部这些字符不会被删掉,也不会被拆开。

解决步骤

  1. 先把文本转成小写。
  2. 用 re.findall 提取 token。模式里的 [a-z]+ 是单词主体,(?:['-][a-z]+)* 表示后面可以重复接上“单撇号或单连字符 + 字母”。
  3. 用 collections.Counter 或普通 dict 统计。

代码示例:

import re

text = "Don't forget the check-in! What about word--word?"

pattern = r"[a-z]+(?:['-][a-z]+)*"
tokens = re.findall(pattern, text.lower())

counts = {}
for token in tokens:
    counts[token] = counts.get(token, 0) + 1

print(counts)

输出:

{"don't": 1, "forget": 1, "the": 1, "check-in": 1, "what": 1, "about": 1, "word": 2}

如果仍想沿用 split() 的流程,也可以先把连续两个以上的连字符替换成空格,再清理首尾标点:

import re

text = "Don't forget the check-in! What about word--word?"
text = re.sub(r"-{2,}", " ", text.lower())

counts = {}
for word in text.split():
    word = re.sub(r"^\W+|\W+$", "", word)
    if word:
        counts[word] = counts.get(word, 0) + 1

print(counts)

这个版本先把两个及以上连续连字符替换成空格,word--word 被拆成 word word,单连字符 check-in 和撇号 don't 保留下来。

注意事项

  • [a-z] 只覆盖 ASCII 小写字母;如果文本含中文、带重音字母或数字,需要调整字符类,例如 [^\W\d_] 或使用 regex 模块的 Unicode 属性。
  • 模式 (?:['-][a-z]+)* 要求每个内部撇号或连字符后面都跟着字母,并且它们不能连续出现;rock'n'roll 这类多个内部撇号可以匹配,但仍建议用测试样例验证。
  • 若需求是保留 -- 作为某种标记而不是分隔符,应改用不同的分词规则。
  • re.sub(r"^\W+|\W+$", "", word) 对 Unicode 标点和下划线行为需注意;\W 不等于“所有标点”。

备注:内容仅供参考。