다른 문자열에 여러 문자열이 있는지 확인
배열의 문자열이 다른 문자열에 있는지 어떻게 확인할 수 있습니까?
처럼:
a = ['a', 'b', 'c']
str = "a123"
if a in str:
print "some of the strings found in str"
else:
print "no strings found in str"
그 코드는 작동하지 않습니다. 달성하려는 것을 보여주기 위해서입니다.
당신은 사용할 수 있습니다 any
:
if any(x in str for x in a):
마찬가지로 목록의 모든 문자열 이 있는지 확인 하려면 all
대신을 사용하십시오 any
.
any()
원하는 모든 것이 True
또는 False
인 경우 가장 좋은 방법 이지만, 어떤 문자열 / 문자열이 일치하는지 구체적으로 알고 싶다면 몇 가지를 사용할 수 있습니다.
첫 번째 일치를 원할 경우 ( False
기본값) :
match = next((x for x in a if x in str), False)
모든 경기 (중복 포함)를 얻으려면 :
matches = [x for x in a if x in str]
중복되지 않은 모든 일치 항목을 얻으려면 (순서 무시) :
matches = {x for x in a if x in str}
중복되지 않은 모든 일치 항목을 올바른 순서로 얻으려면 다음을 수행하십시오.
matches = []
for x in a:
if x in str and x not in matches:
matches.append(x)
줄 이 길어 a
지거나 str
길어질 경우주의해야합니다 . 간단한 솔루션은 O (S * (A ^ 2))를 사용합니다. 여기서 S
길이는 str
A이고에있는 모든 문자열 의 길이의 합입니다 a
. 더 빠른 솔루션을 위해 선형 시간 O (S + A)로 실행되는 문자열 일치에 대한 Aho-Corasick 알고리즘을 살펴보십시오 .
다음과 regex
같이 다양성을 추가하십시오 .
import re
if any(re.findall(r'a|b|c', str, re.IGNORECASE)):
print 'possible matches thanks to regex'
else:
print 'no matches'
또는 목록이 너무 긴 경우- any(re.findall(r'|'.join(a), str, re.IGNORECASE))
a의 요소를 반복해야합니다.
a = ['a', 'b', 'c']
str = "a123"
found_a_string = False
for item in a:
if item in str:
found_a_string = True
if found_a_string:
print "found a match"
else:
print "no match found"
a = ['a', 'b', 'c']
str = "a123"
a_match = [True for match in a if match in str]
if True in a_match:
print "some of the strings found in str"
else:
print "no strings found in str"
jbernadas는 복잡성을 줄이기 위해 이미 Aho-Corasick-Algorithm 을 언급했습니다 .
다음은 파이썬에서 사용하는 한 가지 방법입니다.
기본 Python 파일과 동일한 디렉토리에 넣고 이름을 지정하십시오.
aho_corasick.py
다음 코드를 사용하여 알고리즘을 시도하십시오.
from aho_corasick import aho_corasick #(string, keywords) print(aho_corasick(string, ["keyword1", "keyword2"]))
검색은 대소 문자를 구분합니다.
그것은 당신이 같은 하나의 문자를 확인하고 싶은 경우 (단일 단어 A, E를, 등등 승) 가정 상황에 따라 달라집니다 에이 충분하다
original_word ="hackerearcth"
for 'h' in original_word:
print("YES")
original_word 중 문자를 확인하려면 다음을 사용하십시오.
if any(your_required in yourinput for your_required in original_word ):
해당 original_word에 원하는 모든 입력을 원하면 모든 것을 간단하게 사용하십시오.
original_word = ['h', 'a', 'c', 'k', 'e', 'r', 'e', 'a', 'r', 't', 'h']
yourinput = str(input()).lower()
if all(requested_word in yourinput for requested_word in original_word):
print("yes")
flog = open('test.txt', 'r')
flogLines = flog.readlines()
strlist = ['SUCCESS', 'Done','SUCCESSFUL']
res = False
for line in flogLines:
for fstr in strlist:
if line.find(fstr) != -1:
print('found')
res = True
if res:
print('res true')
else:
print('res false')
나는 이런 종류의 기능을 속도에 사용할 것이다.
def check_string(string, substring_list):
for substring in substring_list:
if substring in string:
return True
return False
data = "firstName and favoriteFood"
mandatory_fields = ['firstName', 'lastName', 'age']
# for each
for field in mandatory_fields:
if field not in data:
print("Error, missing req field {0}".format(field));
# still fine, multiple if statements
if ('firstName' not in data or
'lastName' not in data or
'age' not in data):
print("Error, missing a req field");
# not very readable, list comprehension
missing_fields = [x for x in mandatory_fields if x not in data]
if (len(missing_fields)>0):
print("Error, missing fields {0}".format(", ".join(missing_fields)));
String에서 모든 목록 요소를 사용 가능하게 만드는 방법에 대한 추가 정보
a = ['a', 'b', 'c']
str = "a123"
list(filter(lambda x: x in str, a))
놀랍게도 빠른 접근 방식은 다음을 사용하는 것입니다 set
.
a = ['a', 'b', 'c']
str = "a123"
if set(a) & set(str):
print("some of the strings found in str")
else:
print("no strings found in str")
a
여러 문자 값을 포함하지 않는 경우 작동 합니다 (이 경우 위에any
나열된 대로 사용 ). 그렇다면 a
문자열 로 지정 하는 것이 더 간단합니다 a = 'abc'
.
참고 URL : https://stackoverflow.com/questions/3389574/check-if-multiple-strings-exist-in-another-string
'Programing' 카테고리의 다른 글
순간 js 날짜 시간 비교 (0) | 2020.03.05 |
---|---|
Java SE / EE / ME의 차이점은 무엇입니까? (0) | 2020.03.05 |
SQL Server DB의 모든 인덱스 및 인덱스 열 목록 (0) | 2020.03.05 |
줄 바꿈이나 가로 공간을 만들지 않는 숨겨진 div를 어떻게 만드나요? (0) | 2020.03.05 |
Java의 정적 메소드에서 getClass ()를 호출하는 방법은 무엇입니까? (0) | 2020.03.05 |