2012-03-24 66 views
0
properties = ["color", "font-size", "font-family", "width", "height"] 


inPath = "style.css" 
outPath = "output.txt" 

#Open a file for reading 
file = open(inPath, 'rU') 
if file: 
    # read from the file 
    filecontents = file.read() 
    file.close() 
else: 
    print "Error Opening File." 

#Open a file for writing 
file = open(outPath, 'wb') 
if file: 
    for i in properties: 
     search = i 
     index = filecontents.find(search) 
     file.write(str(index), "\n") 
    file.close() 
else: 
    print "Error Opening File." 

似乎工作,但:搜索,計數並相加 - Python的

  • 它只會搜索關鍵字一次?
  • 它不寫入輸出文件。 function takes exactly 1 argument
  • 我不希望它實際上打印索引,而是顯示關鍵字的次數。

非常感謝

回答

5

首先,你要.count(search),不.find(search),如果你要尋找的是出現的#。

其次,.write()只接受一個參數 - 如果您想寫一個換行符,則需要先連接它,或者撥打.write()兩次。

三,做for i in properties: search = i是多餘的;只需在您的for循環中使用您想要的名稱即可。

for search in properties: 
    cnt = filecontents.count(search) 
    file.write(str(cnt) + "\n") 
+0

輝煌!感謝堆。只是一個問題。例如,如果在「then」中找到「the」,它會增加計數嗎? – 3zzy 2012-03-24 19:08:54

+0

是的。如果只想匹配完整的單詞,則可能需要使用正則表達式,或者使用'.split()'字符串並匹配單個令牌以實現相等。 – Amber 2012-03-24 19:16:50

+0

所以它會計算「顏色」兩次,一次是「顏色」和「背景顏色」?啊! – 3zzy 2012-03-24 19:18:47

0
from itertools import imap 
properties = ("color", "font-size", "font-family", "width", "height") 


inPath = "style.css" 
outPath = "output.txt" 

try: 
    #Open a file for reading 
    filecontents = file(inPath).read() 
except Exception as exc: 
    print exc 
else: 
    #Open a file for writing 
    with open(outPath, 'wb') as out_file: 
     #for property in properties: 
     # out_string = "%s %s\n" 
     # out_file.write(out_string % (
     #      property, filecontents.count(property))) 
     outfile.write('\n'.join(
         imap(str, imap(filecontents.count, properties))))