programing

문자열의 하위 문자열 발생 횟수

procenter 2023. 2. 2. 21:55
반응형

문자열의 하위 문자열 발생 횟수

Python에서 문자열 내에 특정 서브스트링이 존재하는 횟수를 어떻게 셀 수 있습니까?

예를 들어 다음과 같습니다.

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

string.count(substring)를 들면 다음과 같이요.

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

업데이트:

댓글에서 지적된 바와 같이 중복되지 않는 발생에 대해서는 이렇게 하는 것이 좋습니다.중복되는 항목을 계산해야 하는 경우 "Python regex가 중복되는 모든 항목을 검색합니까?"에서 답을 확인하거나 아래 다른 답변을 확인하는 것이 좋습니다.

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

당신의 진의에 따라 다음과 같은 해결책을 제안합니다.

  1. 공백으로 구분된 서브스트링 목록을 의미하며, 모든 서브스트링 중 서브스트링 위치 번호를 알고자 합니다.

    s = 'sub1 sub2 sub3'
    s.split().index('sub2')
    >>> 1
    
  2. 문자열 내의 서브스트링의 문자 위치를 의미합니다.

    s.find('sub2')
    >>> 5
    
  3. sub-bring의 (중복하지 않는) 출현 카운트를 의미합니다.

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

주어진 문자열에서 중복되는 서브스트링을 찾는 가장 좋은 방법은 python 정규식을 사용하는 것입니다.이 경우 정규 표현 라이브러리를 사용하여 중복되는 모든 일치를 찾을 수 있습니다.왼쪽은 서브스트링이고 오른쪽은 일치하는 문자열을 제공합니다.

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

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  

내가 직접 이 알고리즘을 확인해보니 효과가 있었어.

주파수는 다음 두 가지 방법으로 계산할 수 있습니다.

  1. 「 」의 count()str:

    a.count(b)

  2. 또는 다음을 사용할 수 있습니다.

    len(a.split(b))-1

서 ★★★★★a 과 " " " 입니다.b이치노

를 들어, '1: '1'같습니다.str1 = "This is an example and is easy" " is의은.. 'is'는 'is'다. 'is'는 'is'로 하자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

감사합니다!

은 메서드에 것입니다.count중복되는 발생을 고려하지 않고 빈 하위 항목도 신경 쓰지 않습니다.를 들면, '먹다'와 같이요.

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

번째 은 '아예'입니다.21이치노두 번째 답변은 빈 서브 문자열이 asnwer로 0을 반환하는 것이 좋습니다.

다음 코드는 이러한 문제를 해결합니다.

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

질문은 명확하지 않지만, 표면적으로는 당신이 어떤 질문을 하는지 대답하겠습니다.

문자열 S는 L자 길이이며, 여기서 S[1]는 문자열의 첫 번째 문자이고 S[L]는 마지막 문자입니다.이 문자열은 다음과 같습니다.

  • null 문자열 '.'이것들 중 하나가 있습니다.
  • 1 ~ L의 모든 값 A에 대해, A ~L의 모든 값 B에 대해 문자열 S [A].S[B] (포함)L + L-1 + L-2 + ...가 있습니다.이들 문자열 중 1개로 합계 0.5*L*(L+1)입니다.
  • 두 번째 항목에는 S[1]가 포함되어 있습니다.S[L], 즉 원래 문자열 S 전체.

따라서 길이 L의 문자열에는 0.5*L*(L+1)+1개의 서브스트링이 있습니다.이 식을 Python으로 렌더링하면 문자열 내에 존재하는 서브스트링의 수가 표시됩니다.

한 가지 방법은 을 사용하는 것입니다.예를 들어, 발생 횟수를 카운트하려면'hello'을 사용하다

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

리스트 이해력이 있는 원라이너는 어떻습니까?정확히 말하면 93자니까 PEP-8 순수주의 따윈 필요 없어regex.findall 답변은 높은 수준의 코드일 경우 가장 읽기 쉬운 답변입니다.만약 당신이 낮은 수준의 무언가를 만들고 있고, 의존관계를 원하지 않는다면, 이것은 매우 희박하고 비열하다.중복되는 대답을 하고 있습니다.중복되지 않으면 최고점수 답안처럼 카운트를 사용하면 됩니다.

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

모든 서브스트링(중복 포함)을 카운트하려면 이 방법을 사용합니다.

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

나는 "간단하고 분명한 방법"으로 받아들여진 답변을 유지할 것이다. 그러나 중복되는 사건은 다루지 않는다.이러한 정보는 슬라이스를 여러 번 체크함으로써 순진하게 확인할 수 있습니다. sum ("GCAAAAGH"[i:])와 같습니다.범위(len('GCAAAAGH')의 i에 대해서는 'AAA')로 시작한다.

(그것은 3을 낳는다) - Python regex에서 볼 수 있는 것처럼 정규 표현을 트릭으로 할 수 있다.-그리고 그것은 또한 미세한 코드 골프도 만들 수 있다- 이것은 매우 순진하지 않으려는 문자열의 패턴의 중복되는 코르크에 대한 나의 "수제" 카운트이다(적어도 eac에서 새로운 문자열 오브젝트를 생성하지 않는다).h 상호작용):

def find_matches_overlapping(text, pattern):
    lpat = len(pattern) - 1
    matches = []
    text = array("u", text)
    pattern = array("u", pattern)
    indexes = {}
    for i in range(len(text) - lpat):
        if text[i] == pattern[0]:
            indexes[i] = -1
        for index, counter in list(indexes.items()):
            counter += 1
            if text[i] == pattern[counter]:
                if counter == lpat:
                    matches.append(index)
                    del indexes[index]
                else:
                    indexes[index] = counter
            else:
                del indexes[index]
    return matches

def count_matches(text, pattern):
    return len(find_matches_overlapping(text, pattern))

중복 발생:

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

중복 카운트의 경우 다음을 사용할 수 있습니다.

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

중복되지 않는 경우 count() 함수를 사용할 수 있습니다.

string.count(sub_string)

다음은 중복되지 않는 경우와 중복되지 않는 경우 모두 사용할 수 있는 솔루션입니다.명확히 하기 위해: 중복되는 부분 문자열은 마지막 문자가 첫 번째 문자와 동일한 문자열입니다.

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

모든 경우에 대응하는 전원 솔루션을 찾고 있는 경우, 이 기능은 다음과 같이 동작합니다.

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

문자열 내의 서브스트링 수를 알고 싶다면 아래 코드를 사용하십시오.코드가 이해하기 쉽기 때문에 제가 댓글을 생략했습니다.:)

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

다른 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

다음 방법을 사용할 수 있습니다.

def count_substring(string, sub_string):
    x = 0
    for i in range(len(string)):
        if string[i:].startswith(sub_string):
            x += 1
    return x
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)
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)

이것이 이미 살펴본 내용인지는 모르겠지만, 저는 이것을 '폐기할 수 있는' 단어에 대한 해결책으로 생각했습니다.

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

print count

여기서 word는 검색할 단어이고 term은 찾고 있는 용어입니다.

string="abc"
mainstr="ncnabckjdjkabcxcxccccxcxcabc"
count=0
for i in range(0,len(mainstr)):
    k=0
    while(k<len(string)):
        if(string[k]==mainstr[i+k]):
            k+=1
        else:
            break   
    if(k==len(string)):
        count+=1;   
print(count)
import re
d = [m.start() for m in re.finditer(seaching, string)] 
print (d)

그러면 문자열에서 하위 문자열이 발견된 횟수가 검색되고 인덱스가 표시됩니다.

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)

스페이스 구분으로 심플한 문자열의 경우, 딕트를 사용하는 것이 매우 빠릅니다.아래의 코드를 참조해 주세요.

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')

다음 논리는 모든 문자열 및 특수 문자에 적용됩니다.

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"))

다음은 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)
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

언급URL : https://stackoverflow.com/questions/8899905/count-number-of-occurrences-of-a-substring-in-a-string

반응형