从长文本中抽取含有特定关键词的句子,并保存到txt文件,直接写python代码
时间: 2023-09-19 12:06:44 浏览: 102
### 回答1:
可以使用 Python 中的 re 库来实现这个功能。
首先,我们需要使用 Python 的 open 函数打开文本文件,然后使用 read 方法读取文本内容。接着,我们可以使用 re.findall 函数来查找所有包含特定关键词的句子。最后,我们可以使用 Python 的 open 函数再次打开文件,并使用 write 方法将查找到的句子写入文件。
代码如下:
```
import re
# 读取文本文件
with open('input.txt', 'r') as f:
text = f.read()
# 查找所有包含关键词的句子
keyword = '特定关键词'
pattern = r'[^。]*' + keyword + r'[^。]*[。!?]'
sentences = re.findall(pattern, text)
# 将句子写入输出文件
with open('output.txt', 'w') as f:
for sentence in sentences:
f.write(sentence + '\n')
```
请注意,上面的代码使用了正则表达式来匹配句子。正则表达式是一种模式匹配的工具,可以用来查找文本中符合特定规则的内容。在本例中,我们使用了一个匹配任意非句号字符([^。])的模式,然后再匹配一个关键词,最后再匹配一个包含句号、感叹号或问号的模式。这样就可以查找所有包含关键词的句子了。
希望这对你有帮助!
### 回答2:
以下是使用Python代码实现从长文本中抽取含有特定关键词的句子并保存到txt文件的示例:
```python
keyword = "特定关键词"
long_text = "这是一段长文本,其中包含了很多句子。我们需要从中抽取含有特定关键词的句子,并保存到txt文件。"
# 分割长文本为句子列表
sentences = long_text.split("。")
# 提取含有特定关键词的句子
filtered_sentences = []
for sentence in sentences:
if keyword in sentence:
filtered_sentences.append(sentence)
# 保存到txt文件
with open("filtered_sentences.txt", "w", encoding="utf-8") as file:
for sentence in filtered_sentences:
file.write(sentence + "。\n")
```
上述代码中,首先定义了一个特定关键词和一个长文本。然后使用split函数将长文本分割为句子列表。接下来,通过遍历句子列表,检查每个句子是否包含特定关键词,将含有特定关键词的句子添加到过滤后的句子列表中。最后,利用open函数打开一个文件,使用write函数将过滤后的句子写入文件中,保存为txt文件。
### 回答3:
import re
def extract_sentences_with_keyword(long_text, keyword, output_file):
sentences = re.split(r'(?<=\w\.\w.)(?<!Mr.)(?<!Ms.)(?<!Dr.)(?<!Jr.)(?<![A-Z][a-z]\.)(?<=\.|\?)\s', long_text)
keyword_sentences = [sentence for sentence in sentences if re.search(r'\b{}\b'.format(keyword), sentence, re.IGNORECASE)]
with open(output_file, 'w') as file:
for sentence in keyword_sentences:
file.write(sentence + '\n')
# 示例使用
long_text = "这是一个长文本。这些句子包含了特定的关键词python。这个句子不包含关键词。"
keyword = "python"
output_file = "output.txt"
extract_sentences_with_keyword(long_text, keyword, output_file)
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![.zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)