Python编写程序,寻找潜在的无法被jieba默认词库识别的专业词汇,并显示该词语所在的句子,in.txt文本内容,输出到out.txt文件中
时间: 2024-03-13 14:47:13 浏览: 24
好的,下面是Python代码实现:
```python
import jieba
# 读取文本文件
with open('in.txt', 'r', encoding='utf-8') as f:
content = f.read()
# 自定义词典,这里只列出了一些示例词汇,实际使用时可以根据需要添加更多专业词汇
jieba.load_userdict('userdict.txt')
# 分词
sentences = content.split('\n')
for sentence in sentences:
words = jieba.lcut(sentence)
for word in words:
# 判断是否为自定义词典中的词汇
if word in ['词汇1', '词汇2', '词汇3']:
print(sentence.strip())
break
# 输出到文件
with open('out.txt', 'w', encoding='utf-8') as f:
for sentence in sentences:
words = jieba.lcut(sentence)
for word in words:
if word in ['词汇1', '词汇2', '词汇3']:
f.write(sentence.strip() + '\n')
break
```
需要注意的是,自定义词典需要单独创建一个文本文件,每行一个词汇,例如:
```
词汇1
词汇2
词汇3
```
该文件名为`userdict.txt`。