【发布时间】: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文件之前它最初是从中提取的。
-
请检查我的解决方案