求解 python 练习题 5

WriteafunctionnamedmakeWordList()thattakestwoparameters:1.readFileNameisastringthatis... Write a function named makeWordList() that takes two parameters:
1. readFileName is a string that is the name of a file containing text
2. writeFileName is a string that is the name of a file that makeWordList() writes its output to.
Each line in the output file should consist of one of the words in the input file, followed by a space,
followed by the number of occurrences of that word in the input file, including both capitalized and
lower case occurrences. You may assume that the file contains only letters – no numbers or punctuation
marks.
For example, if the input file contains the following text
You can steer yourself any direction you choose
then the output file should have the following content:
any 1
yourself 1
choose 1
you 2
direction 1
can 1
steer 1
展开
 我来答
野人拆
2014-07-21 · TA获得超过1069个赞
知道小有建树答主
回答量:815
采纳率:57%
帮助的人:565万
展开全部
import string
def makeWordList(input_file, output_file):
    
    table = string.maketrans("", "")
    try:
        word_list = dict()
        for line in open(input_file, 'r'):
            line = line.translate(table, string.punctuation).rstrip('\r\n').split(' ')
            for word in line:
                if not word in word_list:
                    word_list[word] = 1
                else:
                    word_list[word] += 1
        f = open(output_file, 'w')
        for k,v in word_list.items():
            line = '%s %s\r\n' % (k,v)
            f.write(line)

    except:
        print input_file,'not exist'
            
            
    
makeWordList('input.txt', 'output.txt')
本回答被网友采纳
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式