我想打开一个文件并获得句子。文件中的句子是跨行的,如下所示:
"He said, 'I'll pay you five pounds a week if I can have it on my own
terms.' I'm a poor woman, sir, and Mr. Warren earns little, and the
money meant much to me. He took out a ten-pound note, and he held it
out to me then and there.
目前,我正在使用此代码:
text = ' '.join(file_to_open.readlines())
sentences = re.split(r' *[\.\?!][\'"\)\]]* *', text)
readlines
删掉句子,有没有解决这个问题的好方法,让它仅获取句子?(没有NLTK)
当前问题:
file_to_read = 'test.txt'
with open(file_to_read) as f:
text = f.read()
import re
word_list = ['Mrs.', 'Mr.']
for i in word_list:
text = re.sub(i, i[:-1], text)
我得到的(在测试案例中)是,太太换了先生,而先生只是先生。我尝试了其他几件事,但似乎没有用。答案可能很简单,但我很想念
如果执行此操作,则您的正则表达式适用于上面的文本:
with open(filename) as f:
text = f.read()
sentences = re.split(r' *[\.\?!][\'"\)\]]* *', text)
唯一的问题是,正则表达式在“先生”中的点上分开。从上面的文本中,因此您需要修复/更改该问题。
解决这个问题的方法(虽然不是完美的)是,您可以消除Mr后面出现的所有点的情况:
text = re.sub(r'(M\w{1,2})\.', r'\1', text) # no for loop needed for this, like there was before
匹配一个'M',后跟最少1个字符,最多2个字母数字字符(\ w {1,3}),后跟一个点。模式的括号部分被分组并捕获,在替换中被称为'\ 1'(或组1,因为您可能会有更多的括号组)。因此从本质上讲,先生或太太是匹配的,但是只捕获了先生或太太部分,然后用不包括点的捕获部分替换了先生或太太。
进而 :
sentences = re.split(r' *[\.\?!][\'"\)\]]* *', text)
将以您想要的方式工作。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句