我想寫一個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