计算字符串中给定子字符串的出现次数

时间:2012-01-17 18:42:33

标签: python string

如何计算Python中字符串中给定子字符串的出现次数?

例如:

>>> 'foo bar foo'.numberOfOccurrences('foo')
2

35 个答案:

答案 0 :(得分:282)

string.count(substring),如:

>>> "abcdabcva".count("ab")
2

<强>更新: 正如评论中所指出的,这是为非重叠出现的方法。如果您需要计算重叠事件的数量,最好查看以下答案:“Python regex find all overlapping matches?”,或者只是查看我的其他答案。

答案 1 :(得分:17)

根据您的真实含义,我提出以下解决方案:

1)你的意思是一个空格分隔的子字符串列表,并想知道所有子字符串中的子字符串位置编号是什么:

s = 'sub1 sub2 sub3'
s.split().index('sub2')
>>> 1

2)你的意思是字符串中子字符串的char位置:

s.find('sub2')
>>> 5

3)你的意思是su-bstring的外观(非重叠)计数

s.count('sub2')
>>> 1
s.count('sub')
>>> 3

答案 2 :(得分:16)

s = 'arunununghhjj'
sb = 'nun'
results = 0
sub_len = len(sb)
for i in range(len(s)):
    if s[i:i+sub_len] == sb:
        results += 1
print results

答案 3 :(得分:10)

您可以使用两种方式计算频率:

  1. 使用count()中的str

    a.count(b)

  2. 或者,您可以使用:

    len(a.split(b))-1

  3. a是字符串,b是要计算其频率的子字符串。

答案 4 :(得分:9)

要在Python 3中查找字符串中子字符串的重叠出现,此算法将执行以下操作:

def count_substring(string,sub_string):
    l=len(sub_string)
    count=0
    for i in range(len(string)-len(sub_string)+1):
        if(string[i:i+len(sub_string)] == sub_string ):      
            count+=1
    return count  

我自己检查了这个算法,但它确实有效。

答案 5 :(得分:9)

在给定字符串中查找重叠子字符串的最佳方法是使用python正则表达式,它将使用正则表达式库找到所有重叠匹配。以下是如何做左边的子串,在右边你将提供匹配的字符串

print len(re.findall('(?=aa)','caaaab'))
3

答案 6 :(得分:6)

涉及方法count的当前最佳答案并不真正计算重叠事件,也不关心空子字符串。 例如:     

>>> a = 'caatatab'
>>> b = 'ata'
>>> print(a.count(b)) #overlapping
1
>>>print(a.count('')) #empty string
9

如果我们考虑重叠的子字符串,第一个答案应该是2而不是1。 至于第二个答案,如果空子字符串返回0作为asnwer,则会更好。

以下代码处理这些事情。

def num_of_patterns(astr,pattern):
    astr, pattern = astr.strip(), pattern.strip()
    if pattern == '': return 0

    ind, count, start_flag = 0,0,0
    while True:
        try:
            if start_flag == 0:
                ind = astr.index(pattern)
                start_flag = 1
            else:
                ind += 1 + astr[ind+1:].index(pattern)
            count += 1
        except:
            break
    return count

现在我们运行它:

>>>num_of_patterns('caatatab', 'ata') #overlapping
2
>>>num_of_patterns('caatatab', '') #empty string
0
>>>num_of_patterns('abcdabcva','ab') #normal
2

答案 7 :(得分:4)

问题不是很清楚,但我会从表面上回答你的问题。

字符串S,长度为L个字符,其中S [1]是字符串的第一个字符,S [L]是最后一个字符,具有以下子字符串:

  • 空字符串''。其中之一就是其中之一。
  • 对于从1到L的每个值A,对于从A到L的每个值B,字符串S [A] .. S [B] (包括的)。这些字符串中有L + L-1 + L-2 + ... 1,用于a 总计0.5 * L *(L + 1)。
  • 注意第二项包括S [1] .. S [L], 即整个原始字符串S.

因此,在长度为L的字符串中有0.5 * L *(L + 1)+ 1个子串。在Python中渲染该表达式,并且您具有字符串中存在的子串数。

答案 8 :(得分:4)

一种方法是使用re.subn。例如,要计算数量 在您可以执行的任何案件组合中出现'hello'

import re
_, count = re.subn(r'hello', '', astring, flags=re.I)
print('Found', count, 'occurrences of "hello"')

答案 9 :(得分:2)

我将接受我接受的答案作为&#34;简单明了的方式来做到这一点&#34; - 但是,这不包括重叠事件。 找出那些可以天真地完成,多次检查切片 - 如:     sum(&#34; GCAAAAAGH&#34; [i:]。startswith(&#34; AAA&#34;)i在范围内(len(&#34; GCAAAAAGH&#34;))

(产生3) - 它可以通过使用正则表达式来完成,如Python regex find all overlapping matches?所示 - 它也可以用于精细的代码打高尔夫球 - 这是我手工制作的&#34;计算字符串中模式的重叠发生次数,这种模式试图不是非常幼稚(至少它不会在每次交互时创建新的字符串对象):

答案 10 :(得分:2)

重叠发生:

def olpcount(string,pattern,case_sensitive=True):
    if case_sensitive != True:
        string  = string.lower()
        pattern = pattern.lower()
    l = len(pattern)
    ct = 0
    for c in range(0,len(string)):
        if string[c:c+l] == pattern:
            ct += 1
    return ct

test = 'my maaather lies over the oceaaan'
print test
print olpcount(test,'a')
print olpcount(test,'aa')
print olpcount(test,'aaa')

<强>结果:

my maaather lies over the oceaaan
6
4
2

答案 11 :(得分:2)

For overlapping count we can use use:

def count_substring(string, sub_string):
    count=0
    beg=0
    while(string.find(sub_string,beg)!=-1) :
        count=count+1
        beg=string.find(sub_string,beg)
        beg=beg+1
    return count

For non-overlapping case we can use count() function:

string.count(sub_string)

答案 12 :(得分:1)

def count_substring(string, sub_string):
    k=len(string)
    m=len(sub_string)
    i=0
    l=0
    count=0
    while l<k:
        if string[l:l+m]==sub_string:
            count=count+1
        l=l+1
    return count

if __name__ == '__main__':
    string = input().strip()
    sub_string = input().strip()

    count = count_substring(string, sub_string)
    print(count)

答案 13 :(得分:1)

场景1:句子中一个单词的出现。 例如:str1 = "This is an example and is easy"。单词“是”的出现。让str2 = "is"

count = str1.count(str2)

场景2:句子中出现模式。

string = "ABCDCDC"
substring = "CDC"

def count_substring(string,sub_string):
len1 = len(string)
len2 = len(sub_string)
j =0
counter = 0
while(j < len1):
    if(string[j] == sub_string[0]):
        if(string[j:j+len2] == sub_string):
            counter += 1
    j += 1

return counter

谢谢!

答案 14 :(得分:1)

具有清单理解力的单线飞机怎么样?从技术上讲,它的93个字符长,让我免于PEP-8的纯粹主义。 regex.findall答案是最高级的代码(如果它是高级代码)。如果您正在构建低级的东西并且不想依赖,那么这是相当精简和卑鄙的。我给出了重叠的答案。显然,只要没有重叠,就可以像最高分数答案那样使用count。

def count_substring(string, sub_string):
    return len([i for i in range(len(string)) if string[i:i+len(sub_string)] == sub_string])

答案 15 :(得分:1)

如果要查找任何字符串中的子字符串数;请使用以下代码。 代码很容易理解,这就是我跳过评论的原因。 :)

string=raw_input()
sub_string=raw_input()
start=0
answer=0
length=len(string)
index=string.find(sub_string,start,length)
while index<>-1:
    start=index+1
    answer=answer+1
    index=string.find(sub_string,start,length)
print answer

答案 16 :(得分:0)

#counting occurence of a substring in another string (overlapping/non overlapping)
s = input('enter the main string: ')# e.g. 'bobazcbobobegbobobgbobobhaklpbobawanbobobobob'
p=input('enter the substring: ')# e.g. 'bob'

counter=0
c=0

for i in range(len(s)-len(p)+1):
    for j in range(len(p)):
        if s[i+j]==p[j]:
            if c<len(p):
                c=c+1
                if c==len(p):
                    counter+=1
                    c=0
                    break
                continue
        else:
            break
print('number of occurences of the substring in the main string is: ',counter)

答案 17 :(得分:0)

我不确定这是否已经看过了,但我认为这是一个'一次性'这个词的解决方案:

for i in xrange(len(word)):
if word[:len(term)] == term:
    count += 1
word = word[1:]

print count

是您要搜索的字词,字词是您要查找的字词

答案 18 :(得分:0)

如果您正在寻找一种在每种情况下都可以使用的电源解决方案,那么此功能应该可以使用:

def count_substring(string, sub_string):
    ans = 0
    for i in range(len(string)-(len(sub_string)-1)):
        if sub_string == string[i:len(sub_string)+i]:
            ans += 1
    return ans

答案 19 :(得分:0)

    private void service(RoutingContext rc) {
    HttpServerResponse response = rc.response();
    JsonObject body = rc.getBodyAsJson();
    String site = body.getString("url");
    response.setStatusCode(200)
            .putHeader("content-type", "application/json; charset=utf-8")
            .end(Json.encodePrettily(site));
}

答案 20 :(得分:0)

def count_substring(string, sub_string):
    inc = 0
    for i in range(0, len(string)):
        slice_object = slice(i,len(sub_string)+i)
        count = len(string[slice_object])
        if(count == len(sub_string)):
            if(sub_string == string[slice_object]):
                inc = inc + 1
    return inc

if __name__ == '__main__':
    string = input().strip()
    sub_string = input().strip()

    count = count_substring(string, sub_string)
    print(count)

答案 21 :(得分:0)

这是一种适用于非重叠和重叠事件的解决方案。需要说明的是:重叠的子字符串是最后一个字符与第一个字符相同的子字符串。

def substr_count(st, sub):
    # If a non-overlapping substring then just
    # use the standard string `count` method
    # to count the substring occurences
    if sub[0] != sub[-1]:
        return st.count(sub)

    # Otherwise, create a copy of the source string,
    # and starting from the index of the first occurence
    # of the substring, adjust the source string to start
    # from subsequent occurences of the substring and keep
    # keep count of these occurences
    _st = st[::]
    start = _st.index(sub)
    cnt = 0

    while start is not None:
        cnt += 1
        try:
            _st = _st[start + len(sub) - 1:]
            start = _st.index(sub)
        except (ValueError, IndexError):
            return cnt

    return cnt

答案 22 :(得分:0)

这将列出字符串中所有出现的事件(也重叠)并对其进行计数

def num_occ(str1, str2):
    l1, l2 = len(str1), len(str2)
    return len([str1[i:i + l2] for i in range(l1 - l2 + 1) if str1[i:i + l2] == str2])

示例:

str1 ='abcabcd'
str2 = 'bc'

将创建此列表,但仅保存 BOLD 值:

[ab, bc ,ca,ab, bc ,cd]

将返回:

len([bc, bc])

答案 23 :(得分:0)

如果要计算所有子字符串(包括重叠的),请使用此方法。

import re
def count_substring(string, sub_string):
    regex = '(?='+sub_string+')'
    # print(regex)
    return len(re.findall(regex,string))

答案 24 :(得分:0)

s = input('enter the main string: ')
p=input('enter the substring: ')
l=[]
for i in range(len(s)):
    l.append(s[i:i+len(p)])
print(l.count(p))

答案 25 :(得分:0)

import re
d = [m.start() for m in re.finditer(seaching, string)] 
print (d)

这将查找字符串中找到的子字符串的次数并显示索引。

答案 26 :(得分:0)

j = 0
    while i < len(string):
        sub_string_out = string[i:len(sub_string)+j]
        if sub_string == sub_string_out:
            count += 1
        i += 1
        j += 1
    return count

答案 27 :(得分:0)

这是Python 3中不区分大小写的解决方案:

s = 'foo bar foo'.upper()
sb = 'foo'.upper()
results = 0
sub_len = len(sb)
for i in range(len(s)):
    if s[i:i+sub_len] == sb:
        results += 1
print(results)

答案 28 :(得分:0)

对于带有空格分隔的简单字符串,使用Dict会非常快,请参见下面的代码

def getStringCount(mnstr:str, sbstr:str='')->int:
    """ Assumes two inputs string giving the string and 
        substring to look for number of occurances 
        Returns the number of occurances of a given string
    """
    x = dict()
    x[sbstr] = 0
    sbstr = sbstr.strip()
    for st in mnstr.split(' '):
        if st not in [sbstr]:
            continue
        try:
            x[st]+=1
        except KeyError:
            x[st] = 1
    return x[sbstr]

s = 'foo bar foo test one two three foo bar'
getStringCount(s,'foo')

答案 29 :(得分:0)

 <tr ng-repeat="rowContent in rows track by $index">
<td>{{rowContent}}</td>
<td>{{rowContent}}</td>
<td>{{rowContent}}</td>
 </tr>

答案 30 :(得分:0)

您可以使用startwith函数

def count_substring(string, sub_string):
x = 0
for i in range(len(string)):
    if string[i:].startswith(sub_string):
        x += 1
return x

Java

上找到有关startswith()的信息

答案 31 :(得分:0)

由于2个以上的人已经提供了此解决方案,因此引发了投票表决失败。我什至赞成其中之一。但是我的可能是新手最容易理解的。

def count_substring(string, sub_string):
    slen  = len(string)
    sslen = len(sub_string)
    range_s = slen - sslen + 1
    count = 0
    for i in range(range_s):
        if (string[i:i+sslen] == sub_string):
            count += 1
    return count

答案 32 :(得分:0)

以下逻辑将适用于所有字符串和特殊字符

def cnt_substr(inp_str, sub_str):

    inp_join_str = ''.join(inp_str.split())

    sub_join_str = ''.join(sub_str.split())

    return inp_join_str.count(sub_join_str)

print(cnt_substr("the sky is   $blue and not greenthe sky is   $blue and not green", "the sky"))

答案 33 :(得分:0)

my_string = """Strings are amongst the most popular data types in Python. 
               We can create the strings by enclosing characters in quotes.
               Python treats single quotes the same as double quotes."""

Count = my_string.lower().strip("\n").split(" ").count("string")
Count = my_string.lower().strip("\n").split(" ").count("strings")
print("The number of occurance of word String is : " , Count)
print("The number of occurance of word Strings is : " , Count)

答案 34 :(得分:-6)

如果您希望计算整个字符串,则可以使用。

Import-Module MSOnline
    $Username = 'o365admin@xxx.onmicrosoft.com'
    $Password = ConvertTo-SecureString 'Password' -AsPlainText -Force
    $credentials = new-object -typename System.Management.Automation.PSCredential -argumentlist $Username,$Password -ErrorAction Stop
    Connect-MsolService -credential $credentials -ErrorAction Stop
    $mfa = New-Object -TypeName Microsoft.Online.Administration.StrongAuthenticationRequirement")
    $mfa.RelyingParty = '*'
    $mfa.RememberDevicesNotIssuedBefore = (Get-Date)
    $auth = @()
    Set-MsolUser -UserPrincipalName user@xxx.onmicrosoft.com -StrongAuthenticationRequirements $auth"