我正在编写一个打开文件的程序,并查找如下所示的行:
X-DSPAM-Confidence: 0.8475.
我想使用split和find函数来提取这些行并将其放在变量中。这是我写的代码:
fname = raw_input("Enter file name: ")
if len(fname) == 0:
fname = 'mbox-short.txt'
fh = open(fname,'r')
total = 0
for line in fh:
if not line.startswith("X-DSPAM-Confidence:"): continue
拜托,请问我现在正在python中开始,所以请给我一些简单的东西,我可以理解以便以后帮助我。拜托,拜托。
答案 0 :(得分:0)
你非常接近,你只需要在继续添加一行list
下面添加一个声明。
fname = raw_input("Enter file name: ")
if len(fname) == 0:
fname = 'mbox-short.txt'
fh = open(fname,'r')
total = 0
lines = []
for line in fh:
if not line.startswith("X-DSPAM-Confidence:"):
continue
lines.append(line) # will only execute if the continue is not executed
fh.close()
您还应该查看with
关键字以打开文件 - 它更安全,更轻松。你会像这样使用它(我也交换了if
的逻辑 - 为你节省了一条线并且不必要的继续):
fname = raw_input("Enter file name: ")
if len(fname) == 0:
fname = 'mbox-short.txt'
total = 0
good_lines = []
with open(fname,'r') as fh:
for line in fh:
if line.startswith("X-DSPAM-Confidence:"):
good_lines.append(line)
如果您只想要这些值,可以使用good_lines
列表进行列表理解,如下所示:
values = [ l.split()[1] for l in good_lines ]
答案 1 :(得分:0)
我认为唯一错误的部分是not
if:
fname = raw_input("Enter file name: ")
if len(fname) == 0:
fname = 'mbox-short.txt'
fh = open(fname,'r')
total = 0
lines = []
for line in fh:
if line.startswith("X-DSPAM-Confidence:"):
lines.append(line)
答案 2 :(得分:0)
首先使用raw_input()
fname = raw_input("Enter file name: ")
然后检查输入字符串是否为空:
if not fname:
fname = 'mbox-short.txt'
然后,打开文件并逐行阅读:
lines = []
with open(fname, 'r') as f:
for line in f.readlines():
if line.startswith("X-DSPAM-Confidence:"):
lines.append(line)
with open() as file
语句只是确保文件对象在您不再需要时关闭。 (退出file.close()
子句时会自动调用with
)
答案 3 :(得分:0)
我知道这个来自哪里,因为我不久前已经完成了这件事。据我记得你需要计算平均值:)
fname = raw_input("Enter file name: ")
fh = open(fname)
count = 0
sum = 0
for line in fh:
if not line.startswith("X-DSPAM-Confidence:") : continue
count = count + 1
pos = line.find(' ')
sum = sum + float(line[pos:])
average = sum/count