-4

我知道如何使用 str.count(sub[, start[, end]]) 来计算字符的出现次数,但是有没有一种简单的方法可以计算以字符串中的字符开头的单词?

b = "this is 100 111 123 test data"
sum(1 for word in b.split() if word.startswith('t'))
2
sum(1 for word in b.split() if word.startswith('1'))
3

有效,但我认为我应该在不使用 sum 或 startswith 的情况下进行计算。

4

4 回答 4

3

给定您的字符串为

instr="我知道如何使用 str.count(sub[, start[, end]]) 来计算字符的出现次数,但是有没有一种简单的方法可以计算以字符串中的字符开头的单词?

如果您需要计算所有以字符串中的字符开头的单词,vowels=set("aeiou")那么您可以这样做

>>> sum(1 for c in re.findall("(\w)\w*",instr) if c in vowels)
11

如果你想找到所有以数字开头的单词,那么

sum(1 for c in re.findall("(\d)\w*",instr) if c in vowels)
于 2012-04-15T21:02:03.893 回答
2

我会这样做:

 s = 'this is a test'
 sum(1 for word in s.split() if word.startswith('t'))
于 2012-04-15T20:42:31.250 回答
0

假设我理解你的问题(一个例子会很有帮助)你可以尝试这样的事情:

 s = 'this is a test'
 target = 't'
 sum([i[0].count(target) for i in s.split()])

会告诉您字符串中的 2 个单词以您的目标字母 ('t') 开头

 sum([1 for i in s.split() if i[0] == target])

是一个等效但更整洁的解决方案(但遇到与评论中指出的相同的问题)

于 2012-04-15T20:38:55.463 回答
-1

首先,您需要获取每个起始字母。为此,您可以在文本上使用列表理解:

In [40]: tgt="This is an example text. There are several words starting with letters."

In [41]: fl=[word[0] for word in tgt.split()]

In [42]: fl
Out[42]: ['T', 'i', 'a', 'e', 't', 'T', 'a', 's', 'w', 's', 'w', 'l']

现在数一数。

对于单个字母,只需在生成的列表上使用 count 方法:

In [43]: fl.count('T')
Out[43]: 2

对于所有字母,只需使用集合和字典:

In [50]: d={}

In [51]: for l in set(fl):
            d[l]=fl.count(l) 

In [52]: d
Out[52]: {'T': 2, 'a': 2, 'e': 1, 'i': 1, 'l': 1, 's': 2, 't': 1, 'w': 2}
于 2012-04-15T21:29:18.440 回答