gpt4 book ai didi

python - 如何计算大数组中字符串的某些元素?

转载 作者:行者123 更新时间:2023-12-01 09:02:31 26 4
gpt4 key购买 nike

我不确定这是否可能,但我有一个包含日期的非常大的数组

a = ['Fri, 19 Aug 2011 19:28:17 -0000',....., 'Wed, 05 Feb 2012 11:00:00 -0000']

我正在尝试寻找是否有一种方法可以计算数组中天和月的频率。在本例中,我尝试计算月份或日期缩写的字符串(例如周五、周一、四月、七月)

最佳答案

您可以使用Counter()来自集合模块。

from collections import Counter

a = ['Fri, 19 Aug 2011 19:28:17 -0000',
'Fri, 09 June 2017 11:11:11 -0000',
'Wed, 05 Feb 2012 11:00:00 -0000']

# this generator splits the dates into words, and cleans word from "".,;-:" characters:
# ['Fri', '19', 'Aug', '2011', '19:28:17', '0000', 'Fri', '09', 'June',
# '2017', '11:11:11', '0000', 'Wed', '05', 'Feb', '2012', '11:00:00', '0000']
# and feeds it to counting:
c = Counter( (x.strip().strip(".,;-:") for word in a for x in word.split() ))

for key in c:
if key.isalpha():
print(key, c[key])

if 仅打印计数器中那些纯“字母”的键,而不是数字:

Fri 2 
Aug 1
June 1
Wed 1
Feb 1

日期名称和月份名称是唯一的pure isalpha() parts您的日期。

完整的c输出:

Counter({'0000': 3, 'Fri': 2, '19': 1, 'Aug': 1, '2011': 1, 
'19:28:17': 1, '09': 1, 'June': 1, '2017': 1, '11:11:11': 1,
'Wed': 1, '05': 1, 'Feb': 1, '2012': 1, '11:00:00': 1})
<小时/>

@AzatIbrakov 评论的改进:

c = Counter( (x.strip().strip(".,;-:") for word in a for x in word.split() 
if x.strip().strip(".,;-:").isalpha()))

已经会在生成步骤中剔除非字母单词。

关于python - 如何计算大数组中字符串的某些元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52358507/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com