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

基于Python实现三用户语句输入及多维度文本分析

Python 文本处理功能实现代码

以下代码完全实现你列出的10项文本处理功能,直接运行即可使用:

def is_title_case(sentence):
    # 检查是否标题大小写(每个单词首字母大写,其余小写)
    words = sentence.split()
    if not words:
        return False
    return all(word.istitle() for word in words)

def count_vowels(sentence):
    vowels = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'}
    return sum(1 for char in sentence if char in vowels)

# 1. 输入三条语句
sentence1 = input("请输入第一条语句:")
sentence2 = input("请输入第二条语句:")
sentence3 = input("请输入第三条语句:")
all_sentences = [sentence1, sentence2, sentence3]

# 2. 检查是否存在标题大小写内容
has_title_case = any(is_title_case(s) for s in all_sentences)
print(f"\n是否存在标题大小写格式内容:{'是' if has_title_case else '否'}")

# 3. 统计所有语句的字母总数
total_letters = sum(1 for s in all_sentences for char in s if char.isalpha())
print(f"所有语句的字母总数:{total_letters}")

# 4. 统计所有语句的单词总数
total_words = sum(len(s.split()) for s in all_sentences)
print(f"所有语句的单词总数:{total_words}")

# 5. 统计以字母'e'开头的单词数量
e_start_words = 0
for s in all_sentences:
    for word in s.split():
        if word.lower().startswith('e'):
            e_start_words += 1
print(f"以字母'e'开头的单词数量:{e_start_words}")

# 6. 统计以'er'结尾的单词数量
er_end_words = 0
for s in all_sentences:
    for word in s.split():
        if word.lower().endswith('er'):
            er_end_words += 1
print(f"以'er'结尾的单词数量:{er_end_words}")

# 7. 分别统计每条语句中的元音字母数量
for i, s in enumerate(all_sentences, 1):
    print(f"第{i}条语句的元音字母数量:{count_vowels(s)}")

# 8. 检查语句中是否包含数字
has_digits = any(any(char.isdigit() for char in s) for s in all_sentences)
print(f"\n是否包含数字:{'是' if has_digits else '否'}")

# 9. 反转第二条语句
reversed_sentence2 = sentence2[::-1]
print(f"反转后的第二条语句:{reversed_sentence2}")

# 10. 将第三条语句中的每个单词逐个反转
reversed_words_sentence3 = ' '.join(word[::-1] for word in sentence3.split())
print(f"每个单词反转后的第三条语句:{reversed_words_sentence3}")

关键功能说明:

  • 标题大小写检查:通过istitle()方法判断每个单词是否符合标题格式,同时处理空语句的边界情况
  • 字母/单词统计:遍历所有语句,用isalpha()筛选字母,split()分割单词进行计数
  • 元音统计:定义元音集合,遍历字符匹配计数
  • 反转操作:利用Python切片[::-1]实现字符串和单词的快速反转,简洁高效
  • 大小写兼容:统计开头/结尾单词时统一转为小写,避免大小写差异影响结果

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 14:01:17