Python.<习题八> 文件与异常(下)
10.读取任意一个Python源代码文件(.py文件),在源代码每行的左边加上行号,且行号与代码间保留一个空格,最后将含有行号的代码保存至一个新的文件内。
with open('实验9-9.py', "r", encoding='utf-8') as file:
lines = file.readlines()
ls = [str(i + 1) + ' ' + line for i, line in enumerate(lines)]
new_content = ''.join(ls)
print(new_content)
with open('实验9-9_带行号.txt', "w", encoding='utf-8') as file:
file.write(new_content)
11.编写程序统计题5中zen.txt文件内单词的词频,并将统计结果保存至一个新的文件内。词频即相同单词出现的次数,如zen.txt文件中better的词频为4,Simple的词频为1.
with open('zen.txt', "r", encoding='utf-8') as file:
content = file.read().lower().replace('\n', '').replace('.', ' ')
words = content.split()
dic_fq = {
}
for w