查找和.txt文件计数的电子邮件

问题描述 投票:0回答:1

这段代码的目标是冠军,但只发现有“从”启动电子邮件。一些需要注意我的教授要求我用三个变量。 .txt文件,我们使用mbox.txt我的代码:

import time

try:
     fh = open('mbox.txt')
except IOError:
     print('Yo, we aint find mbox.txt')
     print("The program will now self-destruct")
     time.sleep(10)
     quit()


email1 = input('First email: ')
email2 = input('Second email: ')
email3 = input('Third email: ')
counter1 = 0
counter2 = 0
counter3 = 0
for line in fh:
     nline = line.rstrip()
     if not line.startswith('From '): continue
     if line.find(email1):
         counter1 += 1
     elif line.find(email2):
         counter2 += 1
     elif line.find(email3):
         counter3 += 1
print('\nFirst email:', email1, '=', counter1)
print('Second email:', email2, '=', counter2)
print('Third email:', email3, '=', counter3)

的输入和输出:

In [1];First email: [email protected]

   ...;Second email: [email protected]

   ...;Third email: [email protected]

Output: First email: [email protected] = 1797
Output: Second email: [email protected] = 0
Output: Third email: [email protected] = 0

所以我的问题是;为什么第一封电子邮件始终打印相同数量1797(其中,从未来的)?我相信这个问题是计数器不会坚持那么,如何跟踪计数器,而他们都指望?

python-3.x parsing
1个回答
0
投票

TLDR;该1797值来自符合From开始所有的行数。

许多可能的解决方案,但最简单的可能是使用str.count(substring)

for line in fh:
    nline = line.rstrip()
    counter1 += line.count(email1)
    counter2 += line.count(email2)
    counter3 += line.count(email3)

print('\nFirst email:', email1, '=', counter1)
print('Second email:', email2, '=', counter2)
print('Third email:', email3, '=', counter3)

输出:

First email: [email protected] = 184
Second email: [email protected] = 33
Third email: [email protected] = 114


Explanation: Where is the 1797 value coming from?

如果未找到该串line.find('[email protected]')返回找到的字符串的位置(字符串索引),和-1。所以,如果发现它总是返回-1如果'[email protected]'没有找到,而5在这种情况下:

'From [email protected] Tue Oct 23 09:23:04 2007\n'
0^^^^^^
1_|||||
2__||||
3___|||
4____||
5_____| starting index of the string is found 

最棘手的部分是现在Python的Truth Value Testing状态:

默认情况下,除非它的类定义了一个对象被认为是真实的,要么返回False一个__bool__()方法,或者不返回零,当与对象称为__len__()方法。

因此,对于每一个确实与From启动线,则下一行被评估:

if line.find(email1): # both cases if `-1` if `5` evaluate to Truthy value
    counter1 += 1

所以基本上与From开始的行都将递增第一计数器,counter1,因而后续elif的不得到遏制,也没有他们的柜台得到增加。

© www.soinside.com 2019 - 2024. All rights reserved.