统计指定英文子串在所有单词中出现的次数(Python)

输入一行英文句子,再输入一个英文字母组成的子串(单词),计算此子串(大写小写视为相同)在整个句子中出现的次数,如果出现的次数超过3次,则将此英文句子的每一个单词均变成小写输出,否则,删除句子中的子串。
输入输出样例:2组
#1
样例输入:
prig is jfdo is
is

样例输出:
prig jfdo

#2
样例输入:
PRis is jfdo is
样例输出:
pris jfdo
好难啊,希望各位指点一下我
#2
样例输入:
PRis is jfdo is is
is
样例输出:
pris jfdo
打错了,真心希望各位帮助

参考代码

#!/usr/bin/env python
#  -*- coding: utf-8 -*-
#python 2.7
import re
print u'请输入英语句子:'
wz = raw_input()
#整句转换为小写
s = wz.lower()
#小写单词的正则表达式
r='[a-z]+'
#找到所有单词
ws = re.findall(r,s)
#定义一个字典来存储单词和次数
dt = {}
for w in ws:
dt[w] = dt.setdefault(w,0)+1
print u'输入查找的英语单词:'
#输入需要查找的单词,转换成小写
fw = raw_input().lower()

if(dt[fw]>3):
print u'该单词出现次数超过3次,现在整句转换为小写。输出:'
print s
else:
print u'该单词出现次数小于等于3次,整句删除该单词。输出'
#re.I忽略大小写匹配
print re.compile(fw,re.I).sub("",wz)

运行测试

c:\pyws>python wenzhang.py
请输入英语句子:
I LOVE THE APPLE, THE big APPle, The red Apple
输入查找的英语单词:
the
该单词出现次数小于等于3次,整句删除该单词。输出
I LOVE  APPLE,  big APPle,  red Apple

c:\pyws>python wenzhang.py
请输入英语句子:
I LOVE THE APPLE, THE big APPle, The red Apple, The delicious Apple
输入查找的英语单词:
the
该单词出现次数超过3次,现在整句转换为小写。输出:
i love the apple, the big apple, the red apple, the delicious apple

温馨提示:答案为网友推荐,仅供参考
相似回答