python - 在文本文件中创建带有句点(句点)的新行

标签 python string text nlp period

<分区>

我想在 python 中显示文本文件中的一个句子,但我想在每个句点(句点)后显示它,新行开始。

例如我的段落是

"Dr. Harrison bought bargain.co.uk for 2.5 million pounds, i.e. he
paid a lot for it. Did he mind? John Smith, Esq. thinks he didn't.
Nevertheless, this isn't true... Well, with a probability of .9 it
isn't."

但我希望它显示如下

"Dr. Harrison bought bargain.co.uk for 2.5 million pounds, i.e. he
paid a lot for it. 
Did he mind? John Smith, Esq. thinks he didn't. 
Nevertheless, this isn't true... 
Well, with a probability of .9 it isn’t."

句子中出现的其他句号(例如网站地址中的“Dr.”、“Esq.”)让这变得越来越困难'.9',当然还有省略号中的前两个点。

对于文本文件中存在的其他时期,我不确定如何处理这个问题,有人可以帮忙吗?谢谢。

“你的任务是编写一个程序,给定一个文本文件的名称,它能够编写它的 每个句子的内容单独一行。” <-- 任务集

最佳答案

这对您的文本起作用:

text = "Dr. Harrison bought bargain.co.uk for 2.5 million pounds, i.e. he "\
       "paid a lot for it. Did he mind? John Smith, Esq. thinks he didn't. "\
       "Nevertheless, this isn't true... Well, with a probability of .9 it "\
       "isn't."

import re

pat = ('(?<!Dr)(?<!Esq)\. +(?=[A-Z])')
print re.sub(pat,'.\n',text)

结果

Dr. Harrison bought bargain.co.uk for 2.5 million pounds, i.e. he paid a lot for it.
Did he mind? John Smith, Esq. thinks he didn't.
Nevertheless, this isn't true...
Well, with a probability of .9 it isn't.

但是不可能有一个正则表达式模式在像人类写作这样复杂的事情中永远不会失败。
请注意,例如,我不得不提出一个否定的回顾断言来排除 Dr. 的情况(我对 Esq. 也做了同样的事情,尽管它并不代表您的文本中存在问题,因为它后面跟着不是以大写字母开头的thinks)
我认为不可能将所有类似的情况提前放入正则表达式模式中,总有一天会发生无法解决的情况。

但是这段代码完成了很多预期的工作。我认为还不错。

关于python - 在文本文件中创建带有句点(句点)的新行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22304149/

相关文章:

c# - 修剪字符串中的字符

mysql - 分隔连接成字符串的数据实体的最佳分隔符是什么?

python - 如何打印到 .txt

python - 尽管安装了开发包,但找不到 tk.h

python - 随着时间的推移计算第二天有多少元素到达

python - PyMongo 导入连接 - 导致 ImportError

html - 如何用 %C3%A0 之类的东西转换文本

python - 如何在 Pandas 中创建 SparseDataFrame?

r - 带引号和分号的 str_extract 正则表达式

java - 使用 Rectangle 选择 iText 中的文本