作业帮 > 综合 > 作业

python 统计单词平均长度,统计a出现的次数

来源:学生作业帮 编辑:作业帮 分类:综合作业 时间:2024/05/17 23:24:23
python 统计单词平均长度,统计a出现的次数
有一个txt文件叫123.txt,里面是很多很多单词
我想统计这些单词的平均长度,然后找出a出现的次数
请根据这个框架写code,包括之前怎样打开那个txt文件
def average_length_of_words():
\x05 pass
def count_occurences(character):
\x05 pass
if(__name__ == "__main__"):
\x05 print(average_length_of_words())
\x05 print(count_occurences("a"))
尝试写了一下.python 2.7.6也测试通过
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import re
from collections import Counter
txt = None
def average_length_of_words():
    l = [len(e) for e in re.findall(r'\w+', txt)]
    return float(sum(l))/len(l)
def count_occurences(character):
    counter = Counter(txt)
    return counter[character]
if(__name__ == "__main__"):
    fp = open('123.txt')
    txt = fp.read()
    fp.close()
    print(average_length_of_words())
    print(count_occurences("a"))