我想写一个python脚本,以便它可以搜索文档中的关键字,并检索关键字所在的整个句子。从我的研究中,我看到acora可以使用,但我仍然发现它不成功。在python中搜索关键字
2
A
回答
0
这就是你可以简单地在shell中执行它的方法。你应该自己写在脚本中。
>>> 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
控制,并且如果其包含,打印它。
您还应该考虑这是区分大小写。您应该考虑您的解决方案很多东西,比如事情!
和?
结束也句子(但有时他们不)
这是一个句子(哈?),或者你认为(!),所以?
将被分裂为
- 这是一个句子(HA
- ),或者你认为(
- ),所以
2
>>> text = """Hello, this is the first sentence. This is the second.
And this may or may not be the third. Am I right? No? lol..."""
>>> import re
>>> s = re.split(r'[.?!:]+', text)
>>> def search(word, sentences):
return [i for i in sentences if re.search(r'\b%s\b' % word, i)]
>>> search('is', s)
['Hello, this is the first sentence', ' This is the second']
0
0
使用grep或egrep命令与python的子进程模块,它可以帮助你。
e.g:
from subprocess import Popen, PIPE
stdout = Popen("grep 'word1' document.txt", shell=True, stdout=PIPE).stdout
#to search 2 different words: stdout = Popen("egrep 'word1|word2' document.txt",
#shell=True, #stdout=PIPE).stdout
data = stdout.read()
data.split('\n')
相关问题
- 1. 在数组中搜索关键字-python
- 2. 关键字搜索
- 3. 关键字搜索
- 4. 关键字搜索
- 5. 搜索关键字
- 6. python - 关键字搜索程序
- 7. python imaplib搜索'NOT'关键字
- 8. Python在字符串中搜索某些关键字
- 9. 按关键字搜索按类别搜索按名称搜索关键字
- 10. 在Lucene中搜索关键字(OR,AND)
- 11. Twitter4j:在标签中搜索关键字
- 12. 在DNN中的关键字搜索
- 13. 在JSON响应中搜索关键字
- 14. NoSQL关键字在大表中搜索
- 15. partial关键字在MySQL中搜索
- 16. 在MongoDB中搜索关键字
- 17. 在多列中搜索关键字
- 18. 按关键字在mongodb/mongoose中搜索
- 19. 在列表中搜索关键字
- 20. 在HTML中搜索关键字
- 21. 在GitHub wiki中搜索关键字
- 22. 通过mysql查询搜索关键字的搜索关键字来计算搜索关键字
- 23. 在python中搜索一个字典键
- 24. MySQL搜索关键字
- 25. mysql关键字搜索
- 26. CHM(HTMLHELP)搜索关键字
- 27. 多关键字搜索
- 28. 排名搜索关键字
- 29. 多个关键字搜索
- 30. 搜索关键字列表
'$猫文档.txt | grep“keyword”' – 2011-06-30 06:25:50
@Franklin与他所说的完全不同。他要求判刑。 –
是的,我意识到grep“关键字”只是为“关键字”。但是我在寻找的是,如果关键字出现,我试图抓住关键字所在的整个句子。有任何想法吗? – Ryan