求解 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 展开
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 展开
展开全部
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')
本回答被网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询