如何在 Python 中解析 iCal 日历文件的 CATEGORIES 组件

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

我正在使用 icalendar 来解析带有 Python 的 .ics 文件。我有遍历事件的循环,我可以阅读开始和结束日期、摘要和与会者。我的问题是我不知道如何 read/parse CATEGORIES 条目。这是我的代码

    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)

在这种形式下,我得到如下所示的输出:

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

所以我要取回 vCategory 对象。如果我尝试使用 from_ical() 获取类别变量的注释掉的版本,我会得到一个错误。

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

这是从 .ics 文件中截取的摘要,工作正常,类别不工作

SUMMARY:Leave
CATEGORIES:other

我做错了什么?

试试这个:

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

它应该给你字节,你可以为文本添加.decode()。