Python练习15
Python日常练习
题目:
现试题文件夹下有一个文本文件input.txt,里面包含一段英文文本,内容如下:
Hi, Mike. I am learning Python. Python is very interesting. I love
it.Do you think it is interesting? Hope you love it.
要求:
读取这个文件并统计文本中每个单词出现的次数,并要求将统计结果按
如下示例格式输出。
注:
单词的分割符约定为空格、换行、逗号(“,”)、句号(“.”)、问号(“?”)。
输出样例:
('it', 3)
('am', 1)
('Hope', 1)
('Python', 2)
('very', 1)
('also', 1)
('is', 2)
('Mike', 1)
('Do', 1)
('you', 2)
('Hi', 1)
('love', 2)
('interesting', 2)
('think', 1)
('I', 2)
('learning', 1)
代码实现
import re
filenameczj = 'input.txt'
def createfileczj():
tt = '''Hi, Mike. I am learning Python. Python is very interesting. I love
it.Do you think it is interesting? Hope you love it. '''
fczj = open(filenameczj, "w")
fczj.write(tt)
fczj.close()
def extractWords(line):
'''extract words form a line of string'''
words = re.split(r'[.\?\t\n, ]+', line)
return words
# end of extractWords
def wordCount(filename):
''' count words from a file'''
########## code start ##########
lines = []
with open(filename) as f:
lines = f.readlines()
words = []
for line in lines:
words.extend(extractWords(line))
wordCount = dict()
for word in words:
if len(word.strip()) > 0:
wordCount[word] = wordCount.get(word, 0) + 1
########## code end ##########
for item in wordCount.items():
print(item, end=";")
# end of wordCount
def main():
createfileczj()
wordCount(filenameczj)
if __name__ == '__main__':
main()
代码效果
有趣的代码需要多加练习!