求救python题目!

用字符串方法做文本处理
1:x=”Only those who have the patience to do simple things perfectly ever acquire the skill to do difficult things easily.”
2:y=”If you have great talents, industry will improve them; if you have but moderate abilities, industry will supply their deficiency.”
a:统计第一句英文中字符数量和单词数量,并给出单词to的索引;
b:将第二句中you换成someone;删除其中的if;
c:分别统计第一句中字符a, b, c, d, e, f, g的数量,并给出其中出现频率最高的字符;
e: 统计第一句中字符o出现的频数,以及占据字符串总长度的百分比;
f: 将第一句话转化为一个列表,每个单词为一个元素。

统计字数量可以用列表表达式:

sum([_ >= 'a' and _ <= 'z' for _ in x.lower()])

统计词数量可以直接将句子拆成词并计算长度:

len(x.split())

在循环中使用字符串的find方法即可得到所有'to'的位置:

i = x.find('to')
while i >= 0:
    print(i)
    i = x.find('to', i+1)

词的替换与删除使用re模块就好。

字频麻烦一点,可以参考词云中的词频统计的方式,以字典进行统计,然后再循环找最大的值就好:

d = {}
for _ in x:
    if _ in 'abcdefg':
        d[_] = d.get(_, 0) + 1
maxkey, maxcount = '', 0
for k, v in d.items():
    if v > maxcount:
        maxkey = k
        maxcount = v
print('"{}":{}'.format(maxkey,d[maxkey]))

至于任务e,处理办法和上面这段基本一样。

任务f,参见第二段代码。

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