搜索,计数和添加 - Python

3zz*_*zzy 0 css python indexing search count

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."
Run Code Online (Sandbox Code Playgroud)

似乎工作,但是:

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

非常感谢

Amb*_*ber 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")
Run Code Online (Sandbox Code Playgroud)