我是靠谱客的博主 复杂黑米,这篇文章主要介绍PR4E第七周作业,现在分享给大家,希望可以做个参考。

本周讲了基本的文本文件操作

首先是打开文件的函数open(),值得注意的是open()返回的不是全部文件内容(内存可能吃不下),而是操作链接内存与因硬盘文件的handle,起到一个connection的作用

然后文本文件中每一行字符的末尾是换行字符“/n”(这是一个字符),注意print函数执行完也会添加一个“/n”字符,可能会有重复换行的问题。当遇到此问题要用strip()函数清楚字符首尾的“/n”字符


复制代码
1
2
fh = open(words.txt) for line in fh
用for循环函数用“line”可以逐行读取文件内容

复制代码
1
inp = fh.read()

可以将文件内容完全读入一个字符串中

 可以用if string.startswith()筛选或者过滤特定行。

用raw_input()输入文件名。


本次有两个作业,分别是

7.1 Write a program that prompts for a file name, then opens that file and reads through the file, and print the contents of the file in upper case. Use the filewords.txt to produce the output below.

You can download the sample data at http://www.pythonlearn.com/code/words.txt

答案:
复制代码
1
2
3
4
5
6
7
8
# Use words.txt as the file name fname = raw_input("Enter file name: ") fh = open(fname) inp = fh.read() inp = inp.upper() inp = inp.rstrip() print inp



7.2  Write a program that prompts for a file name, then opens that file and reads through the file, looking for lines of the form:
复制代码
1
2
X-DSPAM-Confidence: 0.8475
Count these lines and extract the floating point values from each of the lines and compute the average of those values and produce an output as shown below.

You can download the sample data at http://www.pythonlearn.com/code/mbox-short.txtwhen you are testing below enter mbox-short.txt as the file name.

答案

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# Use the file name mbox-short.txt as the file name fname = raw_input("Enter file name: ") fh = open(fname) count = 0 sum = 0 ave = 0 for line in fh: if not line.startswith("X-DSPAM-Confidence:") : continue space = line.find(" ") raw_num = line[space:] num = raw_num.strip() num = num.strip() num = float(num) count = count+1 sum = sum+num ave = sum/count print "Average spam confidence:",ave

其中第二个答案忘记了find函数,一开始是数出space字符的位置然后直接领line = line[20:]的,囧


最后

以上就是复杂黑米最近收集整理的关于PR4E第七周作业的全部内容,更多相关PR4E第七周作业内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(82)

评论列表共有 0 条评论

立即
投稿
返回
顶部