Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/355.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何从给定的文件中吐出所需的行&我如何计算这个世界_Python_Split_Count_Append_Continue - Fatal编程技术网

Python 如何从给定的文件中吐出所需的行&我如何计算这个世界

Python 如何从给定的文件中吐出所需的行&我如何计算这个世界,python,split,count,append,continue,Python,Split,Count,Append,Continue,打开文件mbox-short.txt并逐行读取。当您找到以“From”开头的行时,如以下行所示: 'From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008' 您将使用split解析From行,并打印出行中的第二个单词,即发送消息的人的完整地址。然后在最后打印一个计数 您可以在以下位置下载示例数据: 我尝试了以下几点: fname = input('enter file name:') fhand = open(fname) count

打开文件mbox-short.txt并逐行读取。当您找到以“From”开头的行时,如以下行所示:

'From stephen.marquard@uct.ac.za Sat Jan  5 09:14:16 2008'
您将使用split解析From行,并打印出行中的第二个单词,即发送消息的人的完整地址。然后在最后打印一个计数

您可以在以下位置下载示例数据:

我尝试了以下几点:

fname = input('enter file name:')
fhand = open(fname)
count = 0
for line in fhand:
    if not line.startswith('from '):
         continue
    line = line.rstrip()
    spl = line.split()
    count = count+1
print spl[1]

请告诉我这有什么问题。

您的代码有一些小问题,比如缩进和打字错误。除此之外,一切都很完美

fname=input('enter file name:')
fhand=open(fname)
count=0
for line in fhand:
    if not line.startswith('From '): # change 'from' to 'From'
        continue
    line = line.rstrip()
    spl = line.split()
    count = count+1
    print(spl[1])  # Print every pattern matched, see it's within for loop

print("Total Persons:",count) # Print count
fhand.close()

结尾的print语句没有缩进。问题是Python区分大小写。”从“!=”开始从.jyotish开始,通过这种方式,每行打印两次。那么我们如何管理它。27行需要,但在其程序o/p 54行打印中。将line.startswithFrom更改为line.startswithFrom。我也更新了解决方案以反映这些变化。谢谢