python 中的 Find() 函数
Find() function in python
我刚刚问了一个关于堆栈溢出的问题,这就是我得到的答案。
fname = raw_input("Enter file name: ")
if len(fname) == 0:
fname = 'mbox-short.txt'
fh = open(fname)
count = 0
total = 0
for line in fh:
if not line.startswith("X-DSPAM-Confidence:") : continue
count = count + 1
pos = line.find(' ')
total = total + float(line[pos:])
average = total/count
print 'Average spam confidence:',average
我知道如何使用查找功能,但我不明白答案是如何得到的。我的问题在代码的第 10 行和第 11 行(查找和总计行)。有人可以向我解释一下吗?谢谢。
pos = line.find(' ')
此行表示在 line
中,pos
将首先出现在 space
中。
total = total + float(line[pos:])
这行意味着在 space
之后出现一个字符串,应该转换为 float
并且应该添加到总数中:
例如,如果行是这样的:
X-DSPAM-Confidence: 4.23232
然后 pos
将是 19(space 的位置)并且 line[pos:]
(从 space 到字符串末尾)是 "4.23232"
然后你投float
表示 total = total + 4.23232
我不知道输入的格式,但我可以想象它是这样的:
"texte 123.33"
因此,line.find(" ") 用于查找第一个 space。
之后line[pos:]提取space之后的部分,float将这部分转换为浮点数加到总数上。
在一行(而不是两行)中执行此操作的更好方法应该是:
total = total + float(line.split(" ")[1])
line.find(' ')
Return line
中找到子字符串 " "
的最低索引。
line[pos:]
将尝试从 pos
开始的行中获取子字符串。 (切片 Python 个字符串)。
我刚刚问了一个关于堆栈溢出的问题,这就是我得到的答案。
fname = raw_input("Enter file name: ")
if len(fname) == 0:
fname = 'mbox-short.txt'
fh = open(fname)
count = 0
total = 0
for line in fh:
if not line.startswith("X-DSPAM-Confidence:") : continue
count = count + 1
pos = line.find(' ')
total = total + float(line[pos:])
average = total/count
print 'Average spam confidence:',average
我知道如何使用查找功能,但我不明白答案是如何得到的。我的问题在代码的第 10 行和第 11 行(查找和总计行)。有人可以向我解释一下吗?谢谢。
pos = line.find(' ')
此行表示在 line
中,pos
将首先出现在 space
中。
total = total + float(line[pos:])
这行意味着在 space
之后出现一个字符串,应该转换为 float
并且应该添加到总数中:
例如,如果行是这样的:
X-DSPAM-Confidence: 4.23232
然后 pos
将是 19(space 的位置)并且 line[pos:]
(从 space 到字符串末尾)是 "4.23232"
然后你投float
表示 total = total + 4.23232
我不知道输入的格式,但我可以想象它是这样的: "texte 123.33"
因此,line.find(" ") 用于查找第一个 space。 之后line[pos:]提取space之后的部分,float将这部分转换为浮点数加到总数上。 在一行(而不是两行)中执行此操作的更好方法应该是:
total = total + float(line.split(" ")[1])
line.find(' ')
Return line
中找到子字符串 " "
的最低索引。
line[pos:]
将尝试从 pos
开始的行中获取子字符串。 (切片 Python 个字符串)。