2012-03-24 55 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))))