首页 > 解决方案 > 如何使用python计算文本文件中的特定字符?

问题描述

#Exercise 7: Counting...1...2...3...
#The purpose of this program is to ask a file from the user, open the file 
# and counts the number of comma-separated values in it and report the result to the user

name_file = input("Enter name of file: ")

inf = open(name_file, "r")

count_comma = 0 


line = inf.readline()

for char in line:
    if "," in char:
       count_comma +=1

print (count_comma)
inf.close()

当我运行它时打印 0。为什么?

标签: python-3.x

解决方案


你可能会更好

count_comma = len(line.split(","))

但你必须运行 timeit 才能确定


推荐阅读