You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python处理ICS文件时Summary字段多行合并丢失空格问题

解决icalendar库读取ICS文件SUMMARY字段丢失空格的问题

问题原因

ICS规范中,字段值的换行(折叠)要求续行必须以空格或制表符开头,这样解析时才会保留空格。如果原文件里的SUMMARY分行没有遵守这个规则,icalendar库合并内容时就会直接拼接,导致丢失空格(比如ofBed Rest就是of和Bed直接拼接的结果)。

解决方法

方法1:预处理ICS文件修复折叠格式

读取文件时先修正不符合规范的续行,给非字段开头的续行添加前置空格,再用icalendar解析:

from icalendar import Calendar

# 读取并预处理ICS文件
with open('your_calendar.ics', 'r', encoding='utf-8') as f:
    lines = f.readlines()

processed_lines = []
for idx, line in enumerate(lines):
    line_stripped = line.strip()
    # 判断当前行是否是字段的续行(非首行、不是字段行、上一行是字段行)
    if idx > 0 and ':' not in line_stripped[:10] and ':' in lines[idx-1].strip()[:10]:
        processed_lines.append(' ' + line)
    else:
        processed_lines.append(line)

# 解析处理后的内容
cal = Calendar.from_ical(''.join(processed_lines))

# 验证SUMMARY
for event in cal.walk('VEVENT'):
    summary = event.get('SUMMARY')
    print(summary)

方法2:兜底修复拼接后的字符串

如果无法修改源文件,可以用正则表达式给小写字母接大写字母的位置插入空格(注意:可能误判专有名词,仅作为临时方案):

import re

# 假设summary是从库中读取的字符串
summary = "ofBed RestwithSalazar"
fixed_summary = re.sub(r'([a-z])([A-Z])', r'\1 \2', summary)
print(fixed_summary)  # 输出: of Bed Rest with Salazar

方法3:升级icalendar库

如果是库版本的bug,尝试升级到最新版本:

pip install --upgrade icalendar

内容的提问来源于stack exchange,提问作者Vebjørn Endresen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 11:25:33