概述
本周讲了基本的文本文件操作
首先是打开文件的函数open(),值得注意的是open()返回的不是全部文件内容(内存可能吃不下),而是操作链接内存与因硬盘文件的handle,起到一个connection的作用
然后文本文件中每一行字符的末尾是换行字符“/n”(这是一个字符),注意print函数执行完也会添加一个“/n”字符,可能会有重复换行的问题。当遇到此问题要用strip()函数清楚字符首尾的“/n”字符
fh = open(words.txt)
for line in fh
用for循环函数用“line”可以逐行读取文件内容
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
答案:# 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
X-DSPAM-Confidence: 0.8475Count 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.
答案
# 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第七周作业所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复