如何使用python计算文本文件中的特定字符?

时间:2018-12-04 19:39:08

标签: python-3.x

#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。为什么?

1 个答案:

答案 0 :(得分:-1)

您可能会更好

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

但是您必须运行timeit来确定