Python 中文本文件的条件分块
Conditional chunking of text file in Python
希望这是一个非常直截了当的问题。我有一份成绩单,我正试图将其分成每个演讲者的部分。我目前拥有的代码是;
text = '''
Speaker 1: hello there
this is some text.
Speaker 2: hello there,
this is also some text.
'''
a = text.split('\nSpeaker')
这会按照我的意愿拆分文本,但是我错过了第二个话语中的 'Speaker' 标识符。为了识别目的,我需要保留它。具体来说,我想要获得的结果类似于以下内容;
['Speaker 1: hello there\n\nI am checking to see if this works. \n', ' Speaker2:
Hopefully it will, \n\nit seems pretty straightforward.\n']
欢迎提出任何建议
谢谢
re.split
在多行模式下,匹配 \n
(换行),用零宽度正前瞻匹配 Speaker
((?=Speaker)
):
re.split(r'\n(?=Speaker)', text, flags=re.MULTILINE)
示例:
In [228]: text = '''Speaker 1: hello there
...:
...: this is some text.
...:
...: Speaker 2: hello there,
...:
...: this is also some text.
...: '''
In [229]: re.split(r'\n(?=Speaker)', text, flags=re.MULTILINE)
Out[229]:
['Speaker 1: hello there\n\nthis is some text. \n',
'Speaker 2: hello there, \n\nthis is also some text.\n']
非正则表达式解决方案:
['Speaker' + substr for substr in text.split('Speaker')[1:]]
输出
['Speaker 1: hello there\n\nthis is some text. \n\n',
'Speaker 2: hello there, \n\nthis is also some text.\n']
希望这是一个非常直截了当的问题。我有一份成绩单,我正试图将其分成每个演讲者的部分。我目前拥有的代码是;
text = '''
Speaker 1: hello there
this is some text.
Speaker 2: hello there,
this is also some text.
'''
a = text.split('\nSpeaker')
这会按照我的意愿拆分文本,但是我错过了第二个话语中的 'Speaker' 标识符。为了识别目的,我需要保留它。具体来说,我想要获得的结果类似于以下内容;
['Speaker 1: hello there\n\nI am checking to see if this works. \n', ' Speaker2:
Hopefully it will, \n\nit seems pretty straightforward.\n']
欢迎提出任何建议
谢谢
re.split
在多行模式下,匹配 \n
(换行),用零宽度正前瞻匹配 Speaker
((?=Speaker)
):
re.split(r'\n(?=Speaker)', text, flags=re.MULTILINE)
示例:
In [228]: text = '''Speaker 1: hello there
...:
...: this is some text.
...:
...: Speaker 2: hello there,
...:
...: this is also some text.
...: '''
In [229]: re.split(r'\n(?=Speaker)', text, flags=re.MULTILINE)
Out[229]:
['Speaker 1: hello there\n\nthis is some text. \n',
'Speaker 2: hello there, \n\nthis is also some text.\n']
非正则表达式解决方案:
['Speaker' + substr for substr in text.split('Speaker')[1:]]
输出
['Speaker 1: hello there\n\nthis is some text. \n\n',
'Speaker 2: hello there, \n\nthis is also some text.\n']