在Python中搜索文档中的关键词
我正在尝试写一个Python脚本,让它能够在文档中搜索一个关键词,并找出包含这个关键词的整句话。我查了一下,发现可以用acora这个工具,但我还是没能成功。
4 个回答
0
这就是你可以在命令行中简单实现的方法。你应该自己写个脚本。
>>> text = '''this is sentence 1. and that is sentence
2. and sometimes sentences are good.
when that's sentence 4, there's a good reason. and that's
sentence 5.'''
>>> for line in text.split('.'):
... if 'and' in line:
... print line
...
and that is sentence 2
and sometimes sentences are good
and that's sentence 5
在这里,我用 text
这个变量通过 .split('.')
方法把它分开,然后逐个处理,再用 and
这个词来判断,如果包含这个词,就打印出来。
你还要注意,这个操作是区分大小写的。你在解决问题时需要考虑很多因素,比如以 !
和 ?
结尾的内容也算是句子(但有时候它们并不算)。
这是一个句子(哈?)或者你觉得(!)这样吗?
会被分成:
- 这是一个句子(哈
- )或者你觉得(
- )这样吗
4
当然可以!请提供你想要翻译的内容,我会帮你把它变得更容易理解。