AttributeError

MRAB python at mrabarnett.plus.com
Tue Aug 11 20:58:20 EDT 2015


On 2015-08-12 01:43, Ltc Hotspot wrote:
> The Assignment:
>
>
>
> I'm trying to write Python code to read through a data file and figure 
> out the distribution by hour of the dat for each message in the data file.
>
> Python can pull the hour from the 'From ' line by finding the time and 
> then splitting the string a second time using a colon, i.e., From 
> stephen.marquard at uct.ac.za <mailto:stephen.marquard at uct.ac.za> Sat Jan 
>  5 09:14:16 2008
>
> Finally, accumulated the counts for each hour, print out the counts, 
> sorted by hour as shown below:
>
> name = raw_input("Enter file:")
> if len(name) < 1 : name = "mbox-short.txt"
> handle = open(name)
>
>
> Desired Output:
>
>
> 04 3
> 06 1
> 07 1
> 09 2
> 10 3
> 11 6
> 14 1
> 15 2
> 16 4
> 17 2
> 18 1
> 19 1
>
Well, line.split()[5] isn't the address, it's the time, e.g. "09:14:16". 
You need to do just a little more work to extract the hour.

I don't know what you think you'll achieve by sorting key/value pairs in 
reverse order. What you should be doing is sorting the keys (hours), 
although sorting the pairs of keys and values (i.e., the items) would 
have the same effect. Have a look at the 'sorted' function.

>
>
> Raw data code, available at http://tinyurl.com/ob89r9p
> Embedded data code, available at http://tinyurl.com/qhm4ppq
> Visualization URL link, available at http://tinyurl.com/ozzmffy
>
> Regards,
> Hal
>
> On Tue, Aug 11, 2015 at 5:26 PM, MRAB <python at mrabarnett.plus.com 
> <mailto:python at mrabarnett.plus.com>> wrote:
>
>     On 2015-08-12 01:01, Ltc Hotspot wrote:
>
>         Hi Everyone,
>
>
>         What is the list equivalent to line 12: ncount.sort(reverse=True)
>
>
>         count = dict()
>         fname = raw_input("Enter file name: ")#
>         handle = open (fname, 'r')#
>         for line in handle:
>              if line.startswith("From "):
>                  address = line.split()[5]
>                  line = line.rstrip()
>                  count[address] = count.get(address, 0) + 1
>
>         for key,val in count.items():
>              ncount = (key,val)
>              ncount.sort(reverse=True)
>              print key,val
>
>
>         Error message, reads: AttributeError, line 12, below : 'tuple'
>         object has no attribute 'sort'
>
>         Raw data code, available at http://tinyurl.com/ob89r9p
>         Embedded data code, available at http://tinyurl.com/qhm4ppq
>         Visualization URL link, available at http://tinyurl.com/ozzmffy
>
>     What are you trying to do? Why are you trying to sort a key/value
>     pair in reverse order?
>
>     -- 
>     https://mail.python.org/mailman/listinfo/python-list
>
>




More information about the Python-list mailing list