统计文本文件中的英文单词数量

python 3.5实现

思路: 读取txt文本内容,一行一行读取,去掉换行符,讲文本内容用空格分开,即以单词为单位将文本分开,将单词存到list列表中,使用dict.fromkeys(list,0)方法将列表转换成字典,字典的键是列表中的值,字典的值是0;再次遍历文本,将文本中的单词直接存到字典中,其中 if word in my_dict用来判断字典中是否存在某个键,word.lower()将单词都转为小写,x.capitalize()将单词首字母大写,my_dict.items()以键值对的形式遍历字典

 

代码如下:

def count_word():
    my_dict = {}
    list = []

    with open('test.txt') as f:
        lines = f.readlines()
    for line in lines:
        line = line.strip("\n")
        for word in line.split(' '):
           list.append(word.lower())

    my_dict = my_dict.fromkeys(list, 0)
    for line in lines:
        line = line.strip("\n")
        for word in line.split(' '):
            word = word.lower()
            if word in my_dict:
                my_dict[word] += 1
            else:
                my_dict[word] = 1

    for x, y in my_dict.items():
       print('单词"%s",出现次数为 %s' % (x.capitalize(), y))

 

结果截图

统计文本文件中的英文单词数量_第1张图片

你可能感兴趣的:(Python,刷题)