【问题标题】:How to count the number of occurrences of a string in a file and append it within another file如何计算文件中字符串的出现次数并将其附加到另一个文件中
【发布时间】:2019-02-12 04:21:01
【问题描述】:

我需要计算 .txt 文件中“产品 ID”的出现次数,并让它打印该文件中的数字。我是 python 新手,并试图解决这个问题。我让它在代码中单独工作,但它在运行程序后将数字打印到命令行(因此打印)。我尝试使用 print(count) >> "hardDriveSummary.txt file" 和 print >> count, "hardDriveSummary.txt file" 但无法正常工作。

# Read .xml file and putlines row_name and Product ID into new .txt file
search = 'row_name', 'Product ID'

#source file
with open('20190211-131516_chris_Hard_Drive_Order.xml') as f1:
    #output file
    with open('hardDriveSummary.txt', 'wt') as f2:
        lines = f1.readlines()
        for i, line in enumerate(lines):
            if line.startswith(search):
                f2.write("\n" + line)

#count how many occurances of 'Product ID' in .txt file
def main():

    file  = open('hardDriveSummary.txt', 'r').read()
    team  = "Product ID"
    count = file.count(team)

    print(count)

main()

hardDriveSummary.txt 示例:

Name          Country 1

Product ID                      : 600GB

Name         Country 2

Product ID                      : 600GB

Name           Country 1

Product ID                      : 450GB

.xml 文件的内容:

************* Server Summary *************

Server                      serv01
label                         R720
asset_no                   CNT3NW1
Name                     Country 1
name.1                       City1
Unnamed: 6                     NaN

************* Drive Summary **************

ID                              : 0:1:0
State                           : Failed
Product ID                      : 600GB
Serial No.                      : 6SL5KF5G


************* Server Summary *************

Server                      serv02
label                         R720
asset_no                   BZYGT03
Name                     Country 2
name.1                       City2
Unnamed: 6                     NaN

************* Drive Summary **************

ID                              : 0:1:0
State                           : Failed
Product ID                      : 600GB
Serial No.                      : 6SL5K75G


************* Server Summary *************

Server                      serv03
label                         R720
asset_no                   5GT4N51
Name                     Country 1
name.1                       City1  
Unnamed: 6                     NaN

************* Drive Summary **************

ID                              : 0:1:0
State                           : Failed
Product ID                      : 450GB
Serial No.                      : 6S55K5MG

【问题讨论】:

  • 是“产品ID”两个不同的词
  • 嗨@Jeril,这是数据库中的两个不同的词,在进入xml文件之前它最初是从中提取的。
  • 请检查我的解决方案

标签: python file count


【解决方案1】:

如果您只是想将计数器值标记到文件末尾,则以下代码应该可以工作:

import os

def main():   
    with open('hardDriveSummary.txt', 'ab+') as f:
        term = "Product ID"
        count = f.read().count(term)
        f.seek(os.SEEK_END)  # Because we've already read the entire file. Go to the end before writing otherwise we get an IOError
        f.write('\n'+str(count))

【讨论】:

  • 谢谢@cullzie。我将您的部分添加到代码中,但它没有显示在 .txt 文件中。我已经在我的帖子中添加了一个文件样本,以防万一。再次感谢!
  • 使用您提供的文本文件对我来说工作正常。您可以使用 xml sn-p 更新问题,以便我可以运行整个脚本吗?还有你用的是什么版本的python?
  • 嗨@cullzie,我已经添加了xml文件的内容。我也必须擦洗它。
  • 好的,我现在已经运行了整个程序,它仍在将计数写入文件。请注意,您的 .xml 文件不是 xml 格式。您应该将其重命名为 .txt 文件以避免混淆。在我这边输出示例数据:`产品 ID:600GB 产品 ID:600GB 产品 ID:450GB 3`
  • 嗨@cullzie。我在最后尝试了 main() 并且没有(如你的示例)和没有 main() 我什么都没有得到,但是使用 main() 我得到'0'。 :(
【解决方案2】:

由于Product ID 是两个不同的词,你将整个文本分成两个词组,下面的代码会给你预期的结果:

from collections import Counter
f = open(r"sample.py", "r")
words = f.read().split()
bigrams = zip(words, words[1:])
counts = Counter(bigrams)
data = {' '.join(k): v for k, v in dict(counts).items()}
if 'Product ID' in data:
    print('Count of "Product ID": ', data['Product ID'])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-08
    • 2012-04-24
    • 2012-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-03
    • 2017-03-02
    相关资源
    最近更新 更多