Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/334.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 - Fatal编程技术网

文件读取&;点算及;Python中按小时排序

文件读取&;点算及;Python中按小时排序,python,Python,我是Python新手&这里是我的问题 编写一个程序来通读mbox-short.txt,并计算出每一条消息在一天中按小时的分布情况。通过查找时间,然后使用冒号再次拆分字符串,可以从“from”行中提取小时。 斯蒂芬。marquard@uct.ac.za2008年1月5日星期六09:14:16 累积每小时的计数后,打印计数,按小时排序,如下所示 文件的链接: 这是我的代码: name = raw_input("Enter file:") if len(name) < 1 : name = "

我是Python新手&这里是我的问题

编写一个程序来通读mbox-short.txt,并计算出每一条消息在一天中按小时的分布情况。通过查找时间,然后使用冒号再次拆分字符串,可以从“from”行中提取小时。 斯蒂芬。marquard@uct.ac.za2008年1月5日星期六09:14:16 累积每小时的计数后,打印计数,按小时排序,如下所示

文件的链接:

这是我的代码:

name = raw_input("Enter file:")
if len(name) < 1 : name = "mbox-short.txt"
handle = open(name)

counts = dict()
for line in handle:
    if not line.startswith ("From "):continue
    #words = line.split()

    col = line.find(':')
    coll = col - 2
    print coll


    #zero = line.find('0')
    #one = line.find('1')
    #b = line[ zero or one : col ]
    #print b
    #hour = words[5:6]
    #print hour

    #for line in hour:
     #   hr = line.split(':')
      #  x = hr[1]

    for x in coll:
        counts[x] = counts.get(x,0) + 1

        for key, value in sorted(counts.items()):
            print key, value
name=raw\u输入(“输入文件:”)
如果len(name)<1:name=“mbox short.txt”
句柄=打开(名称)
计数=dict()
对于线输入句柄:
如果不是line.startswith(“From”):继续
#words=line.split()
col=line.find(“:”)
coll=col-2
印刷胶卷
#零=行。查找('0')
#一=行。查找('1')
#b=行[零或一:列]
#打印b
#小时=字[5:6]
#印刷时间
#以小时为单位的线路:
#hr=行。拆分(“:”)
#x=小时[1]
对于coll中的x:
计数[x]=计数。获取(x,0)+1
对于键,排序中的值(counts.items()):
打印键、值
我的第一次尝试是列表拆分(注释),但它不起作用,因为它认为0和1是第一个字母,第二个字母不是数字 第二个是find(:)行,它的部分工作时间是分钟,而不是所需的小时

第一个问题

为什么当我写line.find(:)时,它会自动接受后面的2个数字

第二个问题

为什么当我现在运行程序时,它会给出一个错误 TypeError:“int”对象在第26行不可编辑

第三项质询

为什么它认为0和1是行的第一个和第二个字母,而不是0和1数字

最后 如果可能的话,请给我一点解释来解决这个问题(使用相同的代码来保持我的学习顺序)

谢谢…

这是因为返回找到的子字符串的索引,而不是字符串本身。因此,当您从中减去2,然后尝试循环它时,它会抱怨您试图循环一个整数,并引发一个
TypeError

您可以获取整个时间字符串,如下所示:

time_start = line.find(":")
if time_start == -1:  # not found
    continue
time_string = line[time_start-2:time_start+6]  # slice out the whole time string
然后,您可以通过
进一步拆分
时间字符串
,以获得小时、分钟和秒(例如
小时、分钟、秒=时间字符串。拆分(“:”,2)
请记住这些将是字符串,而不是整数),或者如果您只需要小时:

hour = int(line[time_start-2:time_start])
你可以从这里开始——只要增加你的
dict
值,当你解析完文件后,把所有的东西都整理出来

第一个问题 为什么当我写line.find(:)时,它会自动接受2个数字 之后

str.find()
返回要查找的字符的第一个索引。如果字符串为“From 00:00:00”,则返回7,因为第一个“:”位于索引7处

第二个问题 为什么当我现在运行程序时,它会给出一个错误TypeError:'int' 对象在第26行不可编辑

如上所述,它返回一个
int
,您无法迭代

第三项质询

为什么它认为0和1是行的第一个和第二个字母而不是0& 1个数字

我真的不明白你在这里是什么意思。无论如何,据我所知,您尝试查找出现“0”或“1”的第一个索引,并假设小时的第一个字母是?晚上8点到11点(从2点开始)怎么样

最后,如果可能的话,请帮我解决一下这个问题 请解释(使用相同的代码以保持我的学习顺序)

当然,会是这样的:

for line in f:
    if not line.startswith("From "): continue

    first_colon_index = line.find(":")
    if first_colon_index == -1: # there is no ':'
        continue
    first_char_hour_index = first_colon_index - 2

    # string slicing
    # [a:b] get string from index a to b
    hour = line[first_char_hour_index:first_char_hour_index+2]

    hour_int = int(hour)

    # if key exist, increase by 1. If not, set to 1
    if hour_int in count:
         count[hour_int] += 1
    else:
         count[hour_int] = 1
# print hour & count, in sorting order
for hour in sorted(count):
   print hour, count[hour]
关于字符串切片的部分可能会令人困惑,您可以在网站上阅读更多关于它的内容

您必须确保:在该行中,没有其他“:”或此方法将失败,因为第一个“:”不会是小时和分钟之间的方法

为了确保它有效,最好使用它。比如:

for line in f:
    if not line.startswith("From"): continue

    match = re.search(r'^From.*?([0-9]{2,2}:[0-9]{2,2}:[0-9]{2,2})', line)
    if match:
        time = match.group(1) # hh:mm:ss
        hh = int(time.split(":")[0])
        # if key exist, increase by 1. If not, set to 1
        if hh in count:
             count[hh] += 1
        else:
             count[hh] = 1
# print hour & count, in sorting order
for hour in sorted(count):
   print hour, count[hour]

返回一个数字,例如“从10:20:30开始”。find(“:”)返回7,因为字符串在索引7处包含第一个出现的字符
,而
“从10:20:30开始”。find(“:”,8)
返回10谢谢。。但是我真的需要在不使用setdefault的情况下解决它&如果可能的话使用sort,而不使用out 04 3 06 1 07 1 09 2 10 3 11 6 14 1 15 2 16 4 17 2 18 1 19 1
setdefault
只是if/else的简写。代码已更新。至于排序,你是说打印结果吗?也添加到了代码中。这对我来说非常完美,我也非常理解它,但是我还有最后一个问题,如果你允许我,我需要输出的左边是零,比如04 06 07等等,而不是4 6 7。。为了得到这个作业的分数,问题是为什么在这个解决方案中左零消失了??!!如何用零来输出?谢谢,如果您满意,请考虑将这个答案标记为正确。你需要的是呼叫填充。您可以通过以下方式实现这一点:
'%02d'%number
,这意味着返回长度为2的字符串,如果数字长度小于2个字符,则在
数字之前填充0。i、 e:4=>04,12=>12。在其他答案中还有更多的细节:我确实投了书面答案的赞成票&我也试着投赞成票,但没有,因为我没有足够的声誉..'%02d“。。。。。为我工作,因为它与整数一起工作非常感谢您的回答和解释以及您的耐心:)