python - 修正句子:在标点符号后加空格,但不能在小数点或缩写后加空格
问题描述
当句子没有大写并且标点符号被正确分隔时,我会处理非常混乱的文本。我需要在标点符号 [.,:;)!?] 之后添加空格,但不是十进制数字或缩写。
这是一个例子:
mystring = 'this is my first sentence with (brackets)in it. this is the second?What about this sentence with D.D.T. in it?or this with 4.5?'
这是我到目前为止的地方。
def fix_punctuation(text):
def sentence_case(text):
# Split into sentences. Therefore, find all text that ends
# with punctuation followed by white space or end of string.
sentences = re.findall('[^.!?]+[.!?](?:\s|\Z)', text)
# Capitalize the first letter of each sentence
sentences = [x[0].upper() + x[1:] for x in sentences]
# Combine sentences
return ''.join(sentences)
#add space after punctuation
text = re.sub('([.,;:!?)])', r'\1 ', text)
#capitalize sentences
text = sentence_case(text)
return text
这给了我这个输出:
'This is my first sentence with (brackets) in it. this is the second? What about this sentence with D. D. T. in it? Or this with 4. 5? '
解决方案
您可以使用前瞻来检查该点后面的字符是否不是数字,并且不是另一个点后面的字符(缩写)。您只需要将此应用于该点,并以不同的方式处理其他行尾标点符号。但你也不应该在以下之间注入空格!?
:
text = re.sub(r"(\.)(?=[^\d\s.][^.])|([,;:!?)])(?=\w)", r"\1\2 ", text)
您想要涵盖的场景越多,它就会变得越复杂。
推荐阅读
- python - PySCIPOpt 解决后不释放内存?
- reactjs - 如何在材质 UI Modal 上设置 BorderRadius 属性
- javascript - 如何通过带有 (...) 的单词/字母修剪内容并取决于媒体屏幕
- javascript - throw new mongoose.Error.MissingSchemaError(name) MissingSchemaError: Schema 尚未注册模型“superheros”
- node.js - 如何在节点 js 中使用 json-rpc-client?
- assembly - 递归斐波那契 (NASM)
- node.js - 使用 express-flash 或 connect-flash 会导致空白消息对象
- html - 在 URL 中嵌入 HTML
- excel - 图表 x 轴显示数据点的数量,而不是动态数据集的实际 x 轴值
- c# - 使用 ASP.NET 核心在外部提供程序 API 登录后检索代码