搜索,计数和添加 - Python

时间:2012-03-24 19:00:44

标签: python css search count indexing

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."

似乎有效,但是:

  • 它只搜索一次关键字?
  • 它没有写入输出文件。 function takes exactly 1 argument
  • 我不希望它实际打印索引,而是关键字出现的时间。

非常感谢

2 个答案:

答案 0 :(得分: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")

答案 1 :(得分: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))))