csv中第一位数字的频率,不需要导入

问题描述 投票:2回答:2

我对Python真的是个初学者,我正在我的大学里做课程。如果你有关于这个问题的技巧和建议,请,非常感激。我在编写CSV文件中第一位数字的频率代码时遇到了问题。例如,如果我有以下CSV中的值,我们必须计算出它有多少个。1,2,3,4,5,6,7,8,9,0 出现在每一个数字的第一个数字中,等等,从 5.385686, 3665, 6942, 4053, 7726, 4601, 7302 首位数有一个3,两位数有两个4,一位数有一个3等)

我从文件中删除了除了数字和.以外的任何内容。(使用Ascii表的corrector)我试着先把所有的数据放到列表中,并返回'5.385686',但我不知道下一步该怎么做...

预期的输出。

[[26, 22, 28, 22, 16, 20, 31, 22, 13, 0]]

我只显示了CSV中的部分内容。

5.385686 3665 6942 4053 7726 4601 7302
11754.41657 7859 7002 1502 8754 449 472
800.1759341 2161 4958 3738 5105 1472 2487
1055.19226 7473 3713 4302 3174 6415 9094
1747.798453 2685 5343 3207 2137 1934 1101
2551.157404 3200 4655 2673 4270 821 330
480.7713868 1172 847 3683 9486 2258 6323
19018.97818 3678 5628 1171 7270 8333 2534
505.5652756 7222 4105 6529 169 307 3142
3759.276869 9649 1445 5944 8892 371 8307
4753 6737 906 5057 4401 8698 533
2790 5239 6392 8637 8785 1331 6848
3328 639 3519 7829 6796 3935 2893
6331 2986 6076 1085 7715 8241 5688
[[26, 22, 28, 22, 16, 20, 31, 22, 13, 0]]

这是我目前得到的结果。

def filename():
file = open("sample_accounts.csv", "r")
filecsv = file.read()
filecsv = filecsv.lower()
a = []
b = [ ]

chlist = list(range(128))
del chlist[48:58]
del chlist[46]

for c in chlist:
filecsv = filecsv.replace(chr©," ")
a.append(chlist)

ftlist = filecsv.split()
greet = ftlist
a.append(ftlist)

for i in greet:
return greet[0]
# for i in greet:
# return greet[i]
#
# dic = {}
#
# for word in ftlist:
# dic[word] = dic.get(word,0) + 1
#
# # for item in dic: # **** *
# # print(item, dic[item])
# return greet




d = filename()
python list csv dictionary frequency
2个回答
1
投票

你可以通过将每个数字的计数串入字典中来实现。

count = dict({})
with open('path to your file') as file:
    for line in file.readlines():
        for number in line.split(' '):
            number=number.strip()
            if len(number)<1:
                continue
            digit = number[0]
            if digit.isdigit():
                digit = int(digit)
                if digit in count:
                    count[digit] = count[digit]+1
                else:
                    count[digit] = 1
print(count.values())

输出:

[14, 11, 16, 12, 10, 11, 9, 11, 4]

1
投票

根据问题中的csv片段,你可以做这样的事情。

csv_dat = """[your csv snippet]"""
csv_lst = csv_dat.split(' ') #need to create a list from your snippet; you may already have it in your code
fd_lst = [] #initialize a list for the first digit in each
for item in csv_lst:
    fd_lst.append((item.strip()[0])) #select the first character in each entry
print('digit  frequency')
for x in set(fd_lst): #count only unique characters

    print(x,'\t',fd_lst.count(x))

输出:

digit  frequency
8    10
6    10
9    4
7    9
3    14
1    10
5    9
2    9
4    10
© www.soinside.com 2019 - 2024. All rights reserved.