如何解决字符串计数以包括重复项的问题

时间:2019-07-18 00:29:24

标签: python parsing

我在弄清楚如何获取那里的电子邮件地址总数时遇到问题。我编写的代码只包含非重复地址,在该地址中作业要求包含重复项的总数。

我尝试了for循环,只是将count设置为len()函数,并得到了相同的结果。我重新阅读了这些材料,但对如何包括重复的条目完全感到困惑。

fname = input("Enter file name: ")
if len(fname) == 0:
    fname = "mbox-short.txt"
fh = open(fname)
for line in fh:
    line = line.rstrip()
    if not line.startswith('From '):
        continue
    words = line.split()
    print(words[1])
count = len(words[1])
print("There were", count, "lines in the file with From as the first word")

预期结果:文件中有27行,第一个单词为From

实际结果:文件中有14行,第一个单词为From

1 个答案:

答案 0 :(得分:0)

在从文件读取的循环中增加计数器变量。

count = 0
for line in fh:
    line = line.rstrip()
    if line.startswith('From '):
        words = line.split()
        print(words[1])
        count += 1
print("There were", count, "lines in the file with From as the first word")