Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
273 views
in Technique[技术] by (71.8m points)

How do I parse the CATEGORIES component of an iCal calendar file in Python

I'm using icalendar to parse an .ics file with Python. I have the loop to walk the events and I can read the start and end date, the summary and attendees. My problem is that I can't figure out how to read/parse the CATEGORIES entry. Here's my code

    for event in cal.walk('vevent'):

    dateStart = event.decoded('dtstart')
    dateEnd = event.decoded('dtend')
    summary = event.get('summary')
    category = event.get('categories')
    #category = event.from_ical('categories')
    organizer = event.get('organizer')
    attendeeName = event.get('attendee') #.params['cn']
    print "Start Date: {} End Date: {} Category: {} Attendee: {} Summary: {}".format(dateStart, dateEnd,category,attendeeName,summary)

In this form, I get output that looks like this:

Start Date: 2020-02-21 End Date: 2020-02-22 Category: <icalendar.prop.vCategory object at 0x7f3bfec8a810> Attendee: None Summary: Mahashivarathri

So I'm getting the vCategory object back. If I try the commented out version of getting the category variable using from_ical(), I get an error.

Traceback (most recent call last):
  File "./ical.py", line 73, in <module>
    calTest()
  File "./ical.py", line 66, in calTest
    category = event.from_ical('categories')
  File "/usr/lib/python2.7/site-packages/icalendar/cal.py", line 330, in from_ical
    name, params, vals = line.parts()
  File "/usr/lib/python2.7/site-packages/icalendar/parser.py", line 354, in parts
    % (self, exc)
ValueError: Content line could not be parsed into parts: 'categories': Invalid content line

Here's a snipped from the .ics file with the SUMMARY, which works fine and the CATEGORIES, which doesn't

SUMMARY:Leave
CATEGORIES:other

What am I doing wrong?

question from:https://stackoverflow.com/questions/66055050/how-do-i-parse-the-categories-component-of-an-ical-calendar-file-in-python

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Try this:

category = event.get('categories').to_ical()

It should give you bytes, you can add .decode() for text.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...