gpt4 book ai didi

python - 打开文件并阅读句子

转载 作者:太空宇宙 更新时间:2023-11-03 11:05:29 24 4
gpt4 key购买 nike

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

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com