有点像python/编程新手。。。在
我正试图想出一个正则表达式,它可以处理从文本文件中的一行中提取句子,然后将它们附加到列表中。代码:
import re
txt_list = []
with open('sample.txt', 'r') as txt:
patt = r'.*}[.!?]\s?\n?|.*}.+[.!?]\s?\n?'
read_txt = txt.readlines()
for line in read_txt:
if line == "\n":
txt_list.append("\n")
else:
found = re.findall(patt, line)
for f in found:
txt_list.append(f)
for line in txt_list:
if line == "\n":
print "newline"
else:
print line
以上代码最后5行的打印输出:
^{pr2}$'的内容示例.txt':
^{3}$我已经玩了几个小时的正则表达式,我似乎无法破解它。就目前而言,regex在for lunch?
结尾处不匹配。因此这两个句子What {will|shall|should} we {eat|have} for lunch? Peas by the {thousand|hundred|1000} said Dr. Munchauson; {that|is} what he said.
没有分开;这就是我想要的。在
正则表达式的一些重要细节:
Dr.
总是在每个句子最后一对花括号之前。这就是为什么我尝试使用'}'来建立我的正则表达式。这样我就可以避免使用异常方法,为Dr.
、Jr.
、approx.
等语法创建异常。对于我运行这段代码的每个文件,我个人都要确保在任何句子的最后一个“}”后面没有“误导性句点”。在我想要的输出是:
{Hello there|Hello|Howdy} Dr. Munchauson you {gentleman|fine fellow}!
What {will|shall|should} we {eat|have} for lunch?
Peas by the {thousand|hundred|1000} said Dr. Munchauson; {that|is} what he said.
newline
I am the {very last|last} sentence for this {instance|example}.
如果您不介意添加一个依赖项,那么NLTK库有一个
sent_tokenize
函数,它应该可以满足您的需要,尽管我不完全确定花括号是否会干涉。在描述NLTK方法的论文长达40多页。检测句子边界并不是一件小事。在
我得到的最直观的解决方案是这个。本质上,您需要将
Dr.
和Mr.
标记本身视为原子。在它说:
用在这个上面示例.txt(我加了一行):
^{pr2}$它提供:
相关问题 更多 >
编程相关推荐