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

Python正则提取首字母大写单词后如何过滤单字母词汇并排序

解决方法

要去除结果中的单字母单词,只需修改正则表达式,要求首字母大写后至少包含一个小写字母:

将原正则:

re.findall(r'\b[A-Z][a-z]*\b', line)

替换为:

re.findall(r'\b[A-Z][a-z]+\b', line)

逻辑说明

  • 原表达式中的[a-z]*表示匹配0个或多个小写字母,因此仅单个大写字母的单词会被纳入结果;
  • 修改后的[a-z]+表示匹配1个或多个小写字母,直接排除了只有单个大写字母的单词。

完整脚本示例

import re

filename = input("Enter the file name: ")
words = []

with open(filename, 'r') as f:
    for line in f:
        # 提取首字母大写且后续至少有一个小写字母的单词
        matches = re.findall(r'\b[A-Z][a-z]+\b', line)
        words.extend(matches)

# 去重后按字母顺序排序输出
unique_sorted_words = sorted(list(set(words)))
print(unique_sorted_words)

运行该脚本处理bzip2.txt,结果会自动排除A、C、R这类单字母单词,同时输出按字母排序的目标单词列表。

内容的提问来源于stack exchange,提问作者Shiv Shah

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 17:20:37