【问题标题】:Counting how many times a number appears in a file计算一个数字在文件中出现的次数
【发布时间】:2016-04-10 19:49:22
【问题描述】:
所以我正在获取一个文件并通过我的代码运行它。每行显示在文件中的示例:
100
200
300
100
200
400
我的目标是让我的代码遍历文件中的数字,输出是一个字典,其中数字作为键,它在文件中出现的次数作为值。例如:
{100:2,200:2,300:1,400:1}
这是我到目前为止所整理的。
def counts(filename):
d={}
with open(filename) as f:
for line in f
for number in line:
return d
另外,我可以为此使用 .count() 吗?那么我可以在文件中创建一个数字列表并将它们设置为键,然后为每个数字出现的相应次数设置一个列表并将其设置为键的值吗?
【问题讨论】:
标签:
python
file
dictionary
count
【解决方案1】:
def counts(filename):
d={}
with open(filename) as f:
contents = f.read()
contents = contents.split("\n")
del contents[-1]
contents = map(int, contents)
for content in contents:
if content not in d:
d[content] = 1
else:
d[content] = d[content] + 1
return d
print counts(filename)
o/p
{200: 2, 300: 1, 400: 1, 100: 2}
【解决方案2】:
你可以创建一个矩阵,其中每个位置都可以代表一个数字,其内容代表它在文件中出现的数字。
此外,您可以创建一个比较器,与文件中的数字进行比较,然后增加计数器
【解决方案3】:
对于文件中的每个数字,如果它没有作为键出现在您的字典中,则添加它(计数为 0);无论如何,增加该数字的计数。
【解决方案4】:
我会使用defaultdict 来跟踪您的数字计数:
from collections import defaultdict
frequencies = defaultdict(int)
for number in open('numbers.txt'):
frequencies[int(number)] += 1
for number in sorted(frequencies.keys()):
print(number, ':', frequencies[number])
给予:
100 : 2
200 : 2
300 : 1
400 : 1
使用常规字典,您需要在第一次遇到数字时捕获KeyError:
count = {}
for number in open('numbers.txt'):
try:
count[int(number)] += 1
except KeyError:
count[int(number)] = 1
【解决方案5】:
这使用生成器读取所有行并将它们转换为整数。
from collections import Counter
from csv import reader
def counts(filename):
return Counter(int(line[0]) for line in reader(open(filename)) if line)
c = counts('my_file.csv')
>>> c
Counter({'100': 2, '200': 2, '300': 1, '400': 1})
>>> c.most_commont(5)
[('200', 2), ('100', 2), ('300', 1), ('400', 1)]
>>> dict(c)
{'100': 2, '200': 2, '300': 1, '400': 1}
【解决方案6】:
只使用简单的python:
word_count = {}
with open('temp.txt') as file:
for line in file:
word_count[line[:-1]] = word_count.setdefault(line[:-1], 0) + 1
如果您想使用花哨的库,您可以使用@alexander 的答案Counter。
【解决方案7】:
一种简单的方法是使用Counter,一旦计数完成,它就可以轻松转换为dict。
from collections import Counter
def counts(filename):
with open(filename) as f:
return dict(Counter(int(line) for line in f))
# {200: 2, 100: 2, 300: 1, 400: 1}