2013-10-12 39 views

回答

2

您可以使用文件read()函數「讀取一定數量的數據並將其作爲字符串返回」。

文檔是here

0

使用withopen.read在一起:

with open("/path/to/file") as file: 
    text = file.read() 

with是上下文管理器會自動關閉完成後爲你的文件。

1

至於第二個問題,你可能需要使用正則表達式與word boundary anchors

import re 
with open("myfile.txt") as infile: 
    text = infile.read() 
regex = re.compile(r"\bsearchword\b", re.I) # case-insensitive 
count = len(regex.findall(text)) 
0

您可以一行一行讀,算你有興趣在每行的話,結果添加到小計,並在完成後打印總數。如果您正在處理的文件足夠大,則可以導致交換。