Python实验之——文件与异常

讲真以前学C语言文件和异常就不太会,写这几个题又折腾半天。。。

  1. 统计文件中单词出现的个数。
import re
with open('a.txt', 'r') as f:#注意a.txt和Python放在一个文件目录下
    dictResult = {
     }

    # Find the letters each line
    for line in f.readlines():
        listMatch = re.findall('[a-zA-Z]+', line.lower())  # remember to lower the letters

        # Count
        for eachLetter in listMatch:
            eachLetterCount = len(re.findall(eachLetter, line.lower()))
            dictResult[eachLetter] = dictResult.get(eachLetter, 0) + eachLetterCount

    # Sort the result
    result = sorted(dictResult.items(), key=lambda d: d[1], reverse=True)
    for each in result:
        print (each)

结果:
Python实验之——文件与异常_第1张图片
2. 将 pp.txt 中文件中所有的 love 变为 hate,yes 变为 no,然后生成 pp2.txt。

import sys
import re

f1 = open('pp.txt', 'r+')
f2 = open('pp2.txt', 'w+')

for s in f1.readlines():
    f2.write( s.replace('love','hate').replace('yes','no'))

f1.close()
f2.close()

结果:
在这里插入图片描述
Python实验之——文件与异常_第2张图片
3. 异常处理如下编程,输入一个文件路径或者文件名,查看该文件是否存在,如果存在,打开文件并在屏幕上输出该文件内容;如果不存在,显示“输入的文件未找到!”并要求重新输入;如果文件存在但在读文件过程中发生异常,则显示“文件无法正常读出”,并要求重新输入。
提示: “文件未找到”对应的异常名为:FileNotFoundError,其它异常直接用 except 匹配。

def main() :
    done = False
    while not done :
        try :
            filename = input("Please enter the file name: ")
            f= readFile(filename)
        except FileNotFoundError :
            print("Error: file not found.")
        except  :
            print("Error: file cannot be read.")

def readFile(filename) :
    inFile = open(filename, "r")
    try :
        return readData(inFile)
    finally :
        inFile.close()

def readData(inFile) :
 while True:
    line = inFile.readline()
    if not line: break
    print(line)
#启动程序
main()

Python实验之——文件与异常_第3张图片
坚持!!!

你可能感兴趣的:(Python实验,python)