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
非常感谢
答案 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))))