You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中用正则表达式移除句号且不删除其他内容?

解决正则匹配句号时删除所有内容的问题

你的问题出在正则表达式的元字符使用上:.在正则里是特殊符号,会匹配除换行外的任意字符,所以re.sub(".", "", w)会把单词里的所有内容都清空。

直接修复方案

把匹配句号的正则改成以下两种写法之一:

  1. 转义.,让它匹配字面意义的句号:
    w = re.sub("\.", "", w)
    
  2. 用字符集[,.]一次性匹配逗号和句号,减少一次正则调用:
    w = re.sub("[,.]", "", w)
    

更高效的优化写法

如果标点只出现在单词的首尾(这是文本的常见情况),可以用strip()直接去除首尾的目标字符,比正则更高效:

w = w.strip("., \n")  # 移除首尾的逗号、句号、空格和换行符

修改后的完整代码

import regex as re

word_Dict = {}  # 创建空字典

with open('poem.txt', 'r') as f:
    for l in f:
        words = l.split(' ')
        for w in words:
            w = w.strip()
            # 一次性移除逗号和句号
            w = re.sub("[,.]", "", w)
            
            # 跳过处理后为空的字符串,避免无效统计
            if not w:
                continue
                
            if w in word_Dict:
                word_Dict[w] += 1
            else:
                word_Dict[w] = 1

print(word_Dict)
word_occurances = list(word_Dict.values())
print(word_occurances)

for w, w_count in word_Dict.items():
    print(f'The word "{w}" occured {w_count} times.')

内容的提问来源于stack exchange,提问作者Joy Chatterjee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 02:33:27