【问题标题】:Search, count and add - Python搜索、计数和添加 - Python
【发布时间】:2012-04-08 22:07:33
【问题描述】:
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
  • 我不希望它实际打印索引,而是关键字出现的次数。

非常感谢

【问题讨论】:

    标签: python css search count indexing


    【解决方案1】:

    首先,如果您要查找的是出现次数,您需要的是 .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")
    

    【讨论】:

    • 太棒了!多谢了。只有一个问题。例如,如果在“then”中找到“the”,它会添加计数吗?
    • 是的。如果您只想匹配完整的单词,您可能需要使用正则表达式,或者.split() 字符串并匹配单个标记以实现相等。
    • 所以它会计算两次“颜色”,一次用于“颜色”,一次用于“背景颜色”?啊!
    • @Nimbuz:第四,if file的错误处理无效。如果打开文件失败,内置的open() 将引发异常。请改用try/except
    • 在文件中写入的标准方式是在 python 2.X 上为 print >>file,cnt 在 python 3.X 上为 print(cnt,file=file)
    【解决方案2】:
    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))))
    

    【讨论】:

      猜你喜欢
      • 2019-09-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-11
      • 1970-01-01
      • 2015-07-17
      • 2017-12-07
      • 2014-12-22
      相关资源
      最近更新 更多