Python 如何计算文本文件中的元素数?
我正在尝试计算文本文件中的元素。我知道我漏掉了一个明显的部分,但我无法确定。这是我目前拥有的,它只产生字母“f”的计数,而不是文件:Python 如何计算文本文件中的元素数?,python,Python,我正在尝试计算文本文件中的元素。我知道我漏掉了一个明显的部分,但我无法确定。这是我目前拥有的,它只产生字母“f”的计数,而不是文件: filename = open("output3.txt") f = open("countoutput.txt", "w") import collections for line in filename: for number in line.split(): print(collections.Counter("f"))
filename = open("output3.txt")
f = open("countoutput.txt", "w")
import collections
for line in filename:
for number in line.split():
print(collections.Counter("f"))
break
你能分享你的文件样本吗?您还可以编码计算每行的“f”字母数;你想知道所有文件中“f”的总数?化学元素?对一个显然是python新用户的人来说,一些注释或解释可能会大有帮助。@Aaron我从来没有使用过计数器function@H.Minear这对其他有类似问题的人也有好处,即使你仅仅通过阅读代码就能理解。。
import collections
counts = collections.Counter() # create a new counter
with open(filename) as infile: # open the file for reading
for line in infile:
for number in line.split():
counts.update((number,))
print("Now there are {} instances of {}".format(counts[number], number))
print(counts)