python - 我在 python 中遇到一个问题,即用句子的行结束字符分割文本的一部分

标签 python regex annotations

我想分析 xml 文件,我的程序的一部分将数据分割成句子,但我的行结束字符消失了……我需要它们在句子的开头和结尾处添加带有 xml 标记的注释。

现在我有:

import re

line_end_chars = "!", "?", ".",">"


regexPattern = '|'.join(map(re.escape, line_end_chars))

line_list = re.split(regexPattern, texte)

问题

如果我使用文本运行此代码

" Je pense que cela est compliqué de coder. Où puis-je apprendre?"

这会给我:

["Je pense que cela est compliqué de coder",
"Où puis-je apprendre"] 

这不是我正在寻找的,而是:

["Je pense que cela est compliqué de coder.",
"Où puis-je apprendre?"] 

之后我可以执行 .replace 代码来添加我的 xml 标记。

最佳答案

一种可能的解决方案是使用 re.sub 而不是 re.split,然后使用 str.splitlines():

import re

line_end_chars = "!", "?", ".",">"
s = "Je pense que cela est compliqué de coder. Où puis-je apprendre?"

print( re.sub('(' + '|'.join(re.escape(ch) for ch in line_end_chars) + ')\s*', r'\1\n', s).splitlines() )

打印:

['Je pense que cela est compliqué de coder.', 'Où puis-je apprendre?']

关于python - 我在 python 中遇到一个问题,即用句子的行结束字符分割文本的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59204643/

相关文章:

java - @OneToMany mappedBy 映射到 _____

java - 字符串常量在 SuppressWarnings 注释中不起作用

c# - 正则表达式在遇到分号后停止解析

python - 查找出现两次的最长子串的正则表达式(并且与其双胞胎不相交)

python - 我如何用这些数据绘制条形图

python - pyqt自动连接信号

支持Unicode的Java正则表达式?

java - 如何使用 Lombok 访问 getter 和 setter 方法?

python numpy ValueError : operands could not be broadcast together with shapes

python - 无法安装flask_sqlalchemy ->导入错误: No module named flask_sqlalchemy