计算字符串中的字母总数

时间:2015-10-14 03:49:27

标签: python string python-3.x counting

a =“在宪法权力下,所有人都是平等的,托马斯杰斐逊”

我知道a.count('A')将返回有多少“A”。但是我想知道有多少A,e,c和T并将它们加在一起。非常感谢。

我正在使用Python3

4 个答案:

答案 0 :(得分:5)

查看df_NA <- data.frame(Size = c(800, 850, NA, 1200, NA), Price = c(900, NA, 1300, 1100, 1200), Location = c(NA, 'Downtown', 'Uptown', NA, 'Lakeview'), Rooms = c(1, 2, NA, 4, NA), Bathrooms = c(1, 2, 1, 2, 2), Rent = c('Yes', 'Yes', 'No','Yes', 'No')) index <- apply(is.na(df_NA)*1, 1,paste, collapse = "") s <- split(df_NA, index) i <- 1 # subset using [i] sdf <- data.frame(s[i]) updated_split <- sdf[,colSums(is.na(sdf))<nrow(sdf)] updated_split # X001000.Size X001000.Price X001000.Rooms X001000.Bathrooms X001000.Rent # 1 800 900 1 1 Yes # 4 1200 1100 4 2 Yes # subset using [[i]] sdf <- data.frame(s[[i]]) updated_split <- sdf[,colSums(is.na(sdf))<nrow(sdf)] updated_split # Size Price Rooms Bathrooms Rent # 1 800 900 1 1 Yes # 4 1200 1100 4 2 Yes

collections.Counter

答案 1 :(得分:2)

Python有一个很棒的模块。使用收藏品中的计数器

a.set(i, data.get(i));
b.set(i - a.size(), data.get(i));
data.set(ai + bi, a.get(ai));
data.set(ai + bi, b.get(bi));

它将输出所有字母的字典作为键,值将出现。

答案 2 :(得分:0)

您可以使用正则表达式轻松找到字母总数

import re
p = re.compile("\w")
a = "All men are created equal under the power of the constitution, Thomas Jefferson"
numberOfLetters = len(p.findall(a))

将返回66。

如果你只想要A,e,c和T,你应该使用这个正则表达式:

p = re.compile("[A|e|c|T]")

将返回15。

答案 3 :(得分:0)

尝试了另一种方法

map(lambda x: [x, a.count(x)], 'AecT')

'a'是输入字符串。 'AecT'可根据需要替换所需的字母。

相关问题