【练习题】在字符串中找单词

本文介绍了如何使用Python编写函数,通过正则表达式从输入字符串中提取单词,按长度降序排序并去除重复,最后返回结果。
摘要由CSDN通过智能技术生成

题目:

在给定字符串中找出单词(“单词”由大写字母和小写字母字符构成,其他非字母字符视为单词的间隔,如空格、问号、数字等等;另外单个字母不算单词) 

找到单词后,按照长度进行降序排序(排序时如果长度相同,则按出现的顺序进行排列),然后输出到一个新的字符串中。如果某个单词重复出现多次,则只输出一次;如果整个输入的字符串中没有找到单词,请输出空串。 输出的单词之间使用一个“空格”隔开,最后一个单词后不加空格。

import re

def extract_words(input_str):
    words_dict = {}

    # 使用正则表达式提取单词
    words = re.findall(r'\b[a-zA-Z]{2,}\b', input_str)
    # 全部单词:words = re.findall(r'\b[a-zA-Z]+\b', input_str)

    # 统计单词出现次数和顺序
    for i, word in enumerate(words):
        if word not in words_dict:
            words_dict[word] = (len(word), i)
    return words_dict

def sort_and_output(words_dict):
    sorted_words = sorted(words_dict.items(), key=lambda x: (-x[1][0], x[1][1]))
    output_str = ' '.join(word[0] for word in sorted_words)
    return output_str

def find_unique_words(input_str):
    words_dict = extract_words(input_str)
    if not words_dict:
        return ""
    output_str = sort_and_output(words_dict)
    return output_str

input_str =input()
output_str = find_unique_words(input_str)
print(output_str) 

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值