我被要求在大文件中找到字符串「And」的出現次數,該文件大小爲10GB,並且有1GB RAM。我將如何有效地做到這一點。我回答說我們需要以每個100MB的內存塊讀取文件,然後在每個內存塊中查找「And」的總髮生次數,並保留字符串「And」的累計值。採訪者對我的回答不滿意,他告訴我unix命令grep是如何工作的。寫一個類似於python的代碼,但我不知道答案。我會很感激這個問題的答案。在大文件中發現不匹配內存的字符串
1
A
回答
4
如果您使用generators您可以訪問一個大文件並進行處理。
簡單grep命令,
def command(f):
def g(filenames, **kwa):
lines = readfiles(filenames)
lines = (outline for line in lines for outline in f(line, **kwa))
# lines = (line for line in lines if line is not None)
printlines(lines)
return g
def readfiles(filenames):
for f in filenames:
for line in open(f):
yield line
def printlines(lines):
for line in lines:
print line.strip("\n")
@command
def grep(line, pattern):
if pattern in line:
yield line
if __name__ == '__main__':
import sys
pattern = sys.argv[1]
filenames = sys.argv[2:]
grep(filenames, pattern=pattern)
5
遍歷文件,返回線。在這種情況下,很容易,因爲搜索字符串不包含行尾字符,所以我們不需要擔心跨越行的匹配。
with open("file.txt") as fin:
print sum(line.count('And') for line in fin)
在每一行
>>> help(str.count) Help on method_descriptor: count(...) S.count(sub[, start[, end]]) -> int Return the number of non-overlapping occurrences of substring sub in string S[start:end]. Optional arguments start and end are interpreted as in slice notation.
相關問題
- 1. 發現不匹配的字符串
- 2. 文件的字符串不匹配
- 3. 最大匹配字符串
- 4. 從大文本文件中匹配java字符串問題
- 5. 匹配字符串文字時,「字符大小沒有實現」字符?
- 6. 匹配文字字符串'\ $'
- 7. PHP Preg_match:嘗試匹配字符串中不存在子串的字符串
- 8. 從文件中的字符串不匹配python中的字符串
- 9. 在兩個文件中顯示不匹配的字符串
- 10. 在文件名中間連接匹配字符串的文件
- 11. 兩個大字符串中的部分字符串匹配
- 12. 不匹配字符串內的字母數字字符
- 13. 意圖內發送的字符串不匹配?
- 14. emacs lisp中的字符串匹配匹配任意字符串
- 15. linux在字符串匹配前插入文件內容
- 16. 匹配文本字符串
- 17. 匹配字符「/」在字符串中
- 18. 與bash中的字符串不匹配的列表文件
- 19. 匹配大量的字符串/短語
- 20. 需要得到在文本文件中匹配的字符串
- 21. 在文本文件中循環匹配的字符串
- 22. Ruby:字符串不匹配
- 23. 字符串不能匹配
- 24. 空字符串不匹配。*?
- 25. Perl輸入文件字符串匹配
- 26. 匹配所有出現的字符串
- 27. C++實現字符串匹配的ALG
- 28. 的Python:字符串全字匹配,並附加發現
- 29. 刪除文件中匹配一個字符串但不匹配另一個字符串的行 - SED,BASH?
- 30. 刪除微粒字符串匹配後的文件內容
[這](http://stackoverflow.com/questions/6219141/searching-for-a-string-in-a-large-text-使用
str.count
文件分析 - python中的各種方法)可能會有所幫助。 –不要忘記檢查邊界,如果你不是按行閱讀 –