source

서브스트링의 모든 항목을 찾으려면 어떻게 해야 합니까?

manysource 2022. 11. 3. 21:54

서브스트링의 모든 항목을 찾으려면 어떻게 해야 합니까?

에는 Python이 .string.find() ★★★★★★★★★★★★★★★★★」string.rfind()문자열의 하위 문자열 인덱스를 가져옵니다.

런런? 같은 게 요?string.find_all()발견된 모든 인덱스를 반환할 수 있습니다(처음부터 처음 또는 마지막부터 처음뿐 아니라).

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

string = "test test test test"

print string.find('test') # 0
print string.rfind('test') # 15

#this is the goal
print string.find_all('test') # [0,5,10,15]

원하는 기능을 수행하는 간단한 내장 문자열 함수는 없지만 보다 강력한 정규 표현을 사용할 수 있습니다.

import re
[m.start() for m in re.finditer('test', 'test test test test')]
#[0, 5, 10, 15]

중복되는 일치를 찾으려면 lookahead를 사용하면 됩니다.

[m.start() for m in re.finditer('(?=tt)', 'ttt')]
#[0, 1]

겹치지 않고 모두 역방향 찾기를 원하는 경우, 다음과 같은 식으로 양의 검색과 음의 검색 결과를 결합할 수 있습니다.

search = 'tt'
[m.start() for m in re.finditer('(?=%s)(?!.{1,%d}%s)' % (search, len(search)-1, search), 'ttt')]
#[1]

re.finditer 제너레이터를 반환하기 위해[]한 와 같이()한 번만 반복하면 더 효율적일 수 있는 목록 대신 생성기를 얻을 수 있습니다.

>>> help(str.find)
Help on method_descriptor:

find(...)
    S.find(sub [,start [,end]]) -> int

따라서 델이 직접 구축할 수 있습니다.

def find_all(a_str, sub):
    start = 0
    while True:
        start = a_str.find(sub, start)
        if start == -1: return
        yield start
        start += len(sub) # use start += 1 to find overlapping matches

list(find_all('spam spam spam spam', 'spam')) # [0, 5, 10, 15]

임시 문자열이나 정규식은 필요하지 않습니다.

사용방법:

import re
sentence = input("Give me a sentence ")
word = input("What word would you like to find ")
for match in re.finditer(word, sentence):
    print (match.start(), match.end())

★★★의 word = "this" ★★★★★★★★★★★★★★★★★」sentence = "this is a sentence this this"러음음 음 음 음 、 음 음 음 、 음 음 다 、

(0, 4)
(19, 23)
(24, 28)

(매우 비효율적인) 모든 일치 항목(중복되는 항목까지)을 가져오는 방법은 다음과 같은 방법이 있습니다.

>>> string = "test test test test"
>>> [i for i in range(len(string)) if string.startswith('test', i)]
[0, 5, 10, 15]

다시 말하지만, 오래된 스레드, 하지만 여기 발전기와 플레인(plain)을 사용한 해결책이 있습니다.str.find

def findall(p, s):
    '''Yields all the positions of
    the pattern p in the string s.'''
    i = s.find(p)
    while i != -1:
        yield i
        i = s.find(p, i+1)

x = 'banananassantana'
[(i, x[i:i+2]) for i in findall('na', x)]

돌아온다

[(2, 'na'), (4, 'na'), (6, 'na'), (14, 'na')]

하시면 됩니다.re.finditer()일치시킬 수 있습니다.

>>> import re
>>> aString = 'this is a string where the substring "is" is repeated several times'
>>> print [(a.start(), a.end()) for a in list(re.finditer('is', aString))]
[(2, 4), (5, 7), (38, 40), (42, 44)]

다음과 같은 경우에는 작동하지 않습니다.

In [1]: aString="ababa"

In [2]: print [(a.start(), a.end()) for a in list(re.finditer('aba', aString))]
Output: [(0, 3)]

자, 우리 다시 만나자.

def locations_of_substring(string, substring):
    """Return a list of locations of a substring."""

    substring_length = len(substring)    
    def recurse(locations_found, start):
        location = string.find(substring, start)
        if location != -1:
            return recurse(locations_found + [location], location+substring_length)
        else:
            return locations_found

    return recurse([], 0)

print(locations_of_substring('this is a test for finding this and this', 'this'))
# prints [0, 27, 36]

이런 식으로 정규 표현을 할 필요는 없습니다.

한 명의 캐릭터만 찾고 있다면 다음과 같이 하십시오.

string = "dooobiedoobiedoobie"
match = 'o'
reduce(lambda count, char: count + 1 if char == match else count, string, 0)
# produces 7

또한.

string = "test test test test"
match = "test"
len(string.split(match)) - 1
# produces 4

제 예감으로는, 어느쪽도 (특히 #2)의 퍼포먼스는 형편없다고 생각합니다.

이것은 오래된 이야기지만, 나는 나의 해결책을 공유하고 싶었고 흥미를 가졌다.

def find_all(a_string, sub):
    result = []
    k = 0
    while k < len(a_string):
        k = a_string.find(sub, k)
        if k == -1:
            return result
        else:
            result.append(k)
            k += 1 #change to k += len(sub) to not search overlapping results
    return result

서브스트링이 발견된 위치 목록을 반환해야 합니다.실수나 즉흥적으로 할 수 있는 여지가 보이면 댓글로 남겨주세요.

이것은 re.finder를 사용하는 데 도움이 됩니다.

import re

text = 'This is sample text to test if this pythonic '\
       'program can serve as an indexing platform for '\
       'finding words in a paragraph. It can give '\
       'values as to where the word is located with the '\
       'different examples as stated'

#  find all occurances of the word 'as' in the above text

find_the_word = re.finditer('as', text)

for match in find_the_word:
    print('start {}, end {}, search string \'{}\''.
          format(match.start(), match.end(), match.group()))

이 실은 조금 낡았지만, 저는 이 실이 효과가 있었다.

numberString = "onetwothreefourfivesixseveneightninefiveten"
testString = "five"

marker = 0
while marker < len(numberString):
    try:
        print(numberString.index("five",marker))
        marker = numberString.index("five", marker) + 1
    except ValueError:
        print("String not found")
        marker = len(numberString)

다음 작업을 수행할 수 있습니다.

>>> string = "test test test test"
>>> for index,value in enumerate(string):
    if string[index:index+(len("test"))] == "test":
        print index

0
5
10
15

문서에서 많은 키워드를 찾을 때 플래시 텍스트를 사용합니다.

from flashtext import KeywordProcessor
words = ['test', 'exam', 'quiz']
txt = 'this is a test'
kwp = KeywordProcessor()
kwp.add_keywords_from_list(words)
result = kwp.extract_keywords(txt, span_info=True)

플래시 텍스트는 대량의 검색어 목록에서 regex보다 빠르게 실행됩니다.

이 함수는 문자열 내의 모든 위치를 확인하는 것이 아니라 계산 리소스를 낭비하지 않습니다.내 시도:

def findAll(string,word):
    all_positions=[]
    next_pos=-1
    while True:
        next_pos=string.find(word,next_pos+1)
        if(next_pos<0):
            break
        all_positions.append(next_pos)
    return all_positions

이렇게 부르면 됩니다.

result=findAll('this word is a big word man how many words are there?','word')

다른 사용자가 제공하는 솔루션은 모두 사용 가능한 메서드 find() 또는 사용 가능한 메서드를 기반으로 합니다.

문자열 내의 모든 서브스트링을 찾기 위한 핵심 기본 알고리즘은 무엇입니까?

def find_all(string,substring):
    """
    Function: Returning all the index of substring in a string
    Arguments: String and the search string
    Return:Returning a list
    """
    length = len(substring)
    c=0
    indexes = []
    while c < len(string):
        if string[c:c+length] == substring:
            indexes.append(c)
        c=c+1
    return indexes

또한 str 클래스를 새 클래스로 상속할 수 있으며 아래 함수를 사용할 수 있습니다.

class newstr(str):
def find_all(string,substring):
    """
    Function: Returning all the index of substring in a string
    Arguments: String and the search string
    Return:Returning a list
    """
    length = len(substring)
    c=0
    indexes = []
    while c < len(string):
        if string[c:c+length] == substring:
            indexes.append(c)
        c=c+1
    return indexes

메서드를 호출하다

newstr.find_all('이 답변이 도움이 됩니까?그럼 이거 업투표해!' '이거')

src = input() # we will find substring in this string
sub = input() # substring

res = []
pos = src.find(sub)
while pos != -1:
    res.append(pos)
    pos = src.find(sub, pos + 1)

다음 작업을 수행할 수 있습니다.

import re
str1 = "This dress looks good; you have good taste in clothes."
substr = "good"
result = [_.start() for _ in re.finditer(substr, str1)]
# result = [17, 32]

비토닉 방식은 다음과 같습니다.

mystring = 'Hello World, this should work!'
find_all = lambda c,s: [x for x in range(c.find(s), len(c)) if c[x] == s]

# s represents the search string
# c represents the character string

find_all(mystring,'o')    # will return all positions of 'o'

[4, 7, 20, 26] 
>>> 

이것은 해커랭크의 유사한 질문에 대한 해결책이다.이게 도움이 됐으면 좋겠어요.

import re
a = input()
b = input()
if b not in a:
    print((-1,-1))
else:
    #create two list as
    start_indc = [m.start() for m in re.finditer('(?=' + b + ')', a)]
    for i in range(len(start_indc)):
        print((start_indc[i], start_indc[i]+len(b)-1))

출력:

aaadaa
aa
(0, 1)
(1, 2)
(4, 5)

만약 당신이 numpy만을 사용하고 싶다면, 여기에 해결책이 있습니다.

import numpy as np

S= "test test test test"
S2 = 'test'
inds = np.cumsum([len(k)+len(S2) for k in S.split(S2)[:-1]])- len(S2)
print(inds)

re(regex)를 사용하지 않고 사용하는 경우:

find_all = lambda _str,_w : [ i for i in range(len(_str)) if _str.startswith(_w,i) ]

string = "test test test test"
print( find_all(string, 'test') ) # >>> [0, 5, 10, 15]

다음은 할당식(Python 3.8 이후 새로운 기능)을 사용하여 생각해낸 솔루션입니다.

string = "test test test test"
phrase = "test"
start = -1
result = [(start := string.find(phrase, start + 1)) for _ in range(string.count(phrase))]

출력:

[0, 5, 10, 15]

아래 코드를 봐주세요.

#!/usr/bin/env python
# coding:utf-8
'''黄哥Python'''


def get_substring_indices(text, s):
    result = [i for i in range(len(text)) if text.startswith(s, i)]
    return result


if __name__ == '__main__':
    text = "How much wood would a wood chuck chuck if a wood chuck could chuck wood?"
    s = 'wood'
    print get_substring_indices(text, s)
def find_index(string, let):
    enumerated = [place  for place, letter in enumerate(string) if letter == let]
    return enumerated

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

find_index("hey doode find d", "d") 

반환:

[4, 7, 13, 15]

OP가 요구한 것은 아니지만 분할 함수를 사용하여 모든 서브스트링이 발생하지 않는 곳의 목록을 얻을 수도 있습니다.OP는 코드의 최종 목표를 지정하지 않았습니다만, 어쨌든 기판을 떼어내는 것이 목적이라면, 이것은 단순한 원라이너일 가능성이 있습니다.보다 큰 문자열로 이 작업을 수행하는 보다 효율적인 방법이 있을 수 있습니다.이 경우 정규 표현을 사용하는 것이 좋습니다.

# Extract all non-substrings
s = "an-example-string"
s_no_dash = s.split('-')
# >>> s_no_dash
# ['an', 'example', 'string']

# Or extract and join them into a sentence
s_no_dash2 = ' '.join(s.split('-'))
# >>> s_no_dash2
# 'an example string'

다른 답변들을 간략히 훑어보았습니다. 만약 이게 이미 저 위에 있다면 사과드립니다.

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

if __name__ == '__main__':
    string = input().strip()
    sub_string = input().strip()
    
    count = count_substring(string, sub_string)
    print(count)

같은 문제로 실행해서 다음과 같이 했습니다.

hw = 'Hello oh World!'
list_hw = list(hw)
o_in_hw = []

while True:
    o = hw.find('o')
    if o != -1:
        o_in_hw.append(o)
        list_hw[o] = ' '
        hw = ''.join(list_hw)
    else:
        print(o_in_hw)
        break

저는 코딩에 익숙하지 않기 때문에 단순화할 수 있을 것입니다(계속 사용할 계획이라면 당연히 함수로 만들 수 있습니다).

모든 것이 내가 하고 있는 일에 의도한 대로 작동한다.

편집: 이것은 단일 문자만을 위한 것으로, 변수가 변경되기 때문에, 새로운 변수에 문자열의 카피를 작성해 보존할 필요가 있습니다.그 이유는 문자열의 카피는 코드에 넣지 않았기 때문입니다.그것은, 알기 쉽고, 동작의 구조를 나타내기 위해서입니다.

주어진 문자열에서 발생한 모든 문자를 찾아 사전으로 반환하려면: hello 결과: {'h':1, 'e':1, 'l':2, 'o':1}

def count(string):
   result = {}
   if(string):
     for i in string:
       result[i] = string.count(i)
     return result
   return {}

아니면 이렇게 하는 거야

from collections import Counter

   def count(string):
      return Counter(string)

이거 먹어봐, 나한텐 효과가 있었어!

x=input('enter the string')
y=input('enter the substring')
z,r=x.find(y),x.rfind(y)
while z!=r:
        print(z,r,end=' ')
        z=z+len(y)
        r=r-len(y)
        z,r=x.find(y,z,r),x.rfind(y,z,r)

슬라이스를 통해 가능한 모든 조합을 찾아 목록에 추가하고 다음을 사용하여 발생하는 횟수를 찾습니다.count기능.

s=input()
n=len(s)
l=[]
f=input()
print(s[0])
for i in range(0,n):
    for j in range(1,n+1):
        l.append(s[i:j])
if f in l:
    print(l.count(f))

언급URL : https://stackoverflow.com/questions/4664850/how-to-find-all-occurrences-of-a-substring