python - 打开文件并阅读句子

标签 python regex file readlines

我想打开一个文件并获取句子。文件中的句子跨行,像这样:

"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)

我得到的结果(在测试用例中)是 Mrs. 变成了 Mr 而 Mr. 只是 Mr 。我尝试了其他几件事,但似乎没有用。答案可能很简单,但我想念它

最佳答案

如果您这样做,您的正则表达式将对上面的文本起作用:

with open(filename) as f:
    text = f.read()

sentences = re.split(r' *[\.\?!][\'"\)\]]* *', text)

唯一的问题是,正则表达式在“Mr.”中的点上 split 。从你上面的文字,所以你需要修复/改变它。

解决这个问题的一个方法虽然不完美,但是您可以去掉 Mr: 之后所有出现的点

text = re.sub(r'(M\w{1,2})\.', r'\1', text) # no for loop needed for this, like there was before

this 匹配一个“M”,后跟最少 1 个,最多 2 个字母数字字符 (\w{1,3}),后跟一个点。模式的带括号的部分被分组和捕获,并在替换中引用为“\1”(或第 1 组,因为您可以有更多带括号的组)。所以本质上,Mr. 或 Mrs. 是匹配的,但只有 Mr 或 Mrs. 部分被捕获,然后 Mr. 或 Mrs. 被捕获的部分替换,不包括点。

然后:

sentences = re.split(r' *[\.\?!][\'"\)\]]* *', text)

将按照您想要的方式工作。

关于python - 打开文件并阅读句子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20719247/

相关文章:

python - 没有名为 'PyQt5.sip' 的模块

检测到 Chromedriver 的 Python Selenium

python - 在正则表达式模式中获取捕获组的起始位置

php - php 中的字符串到压缩流

python - 如何组织Python源代码文件?

以下语言的正则表达式

java 比较两个 Pattern 对象

c - 将数百万次写入文件会破坏我的硬盘吗?

file - 如何使用 Go 字节有效地替换两个字符串分隔符之间出现的字符串?

python - while 循环中的字符串连接不起作用