문제..
특정 텍스트 패턴에 대한 문자열의 시작 또는 끝을 확인해야 한다고 가정합니다. 일반적인 패턴은 파일 이름 확장자일 수 있지만 무엇이든 될 수 있습니다. 이 작업을 수행하는 방법에 대한 몇 가지 방법을 보여 드리겠습니다.
Startswith() 메소드
문자열의 시작을 확인하는 간단한 방법은 startswith() 메서드를 사용하는 것입니다.
예시
text = "Is USA colder than Australia?" print(f"output \n {text.startswith('Is')}")
출력
True
예시
filename = "Hello_world.txt" print(f"output \n {filename.startswith('Hello')}")
출력
True
예시
site_url = 'https://www.something.com' print(f"output \n {site_url.startswith('http:')}")
출력
False
예시
print(f"output \n {site_url.startswith('https:')}")
출력
True
endswith() 메서드.
문자열의 끝을 확인하는 간단한 방법은 endwith() 메서드를 사용하는 것입니다.
출력
text = "Is USA colder than Australia?" print(f"output \n {text.endswith('?')}")
출력
True
예시
filename = "Hello_world.txt" print(f"output \n {filename.endswith('.txt')}")
출력
True
이제 위의 방법으로 다중 선택을 확인하려면 튜플을 제공해야 합니다. 일반적인 사용법 중 하나는 파일 확장자를 확인하는 것입니다. 디렉터리에서 ".txt" 및 ".csv" 파일의 유효성을 검사해야 한다고 가정해 보겠습니다.
import os filenames = os.listdir('.')
# Let us first check if there are files print(f"output \n {any(name.endswith(('.csv',',txt')) for name in filenames)}")
출력
True
출력
[name for name in filenames if name.endswith(('.csv', '.txt')) ]
출력
['file1.csv', 'HRDataset.csv', 'Input.csv', 'input.txt', 'input_copy.txt', 'movies_data.csv', 'my_html_data_to_csv.csv', 'temporary_file1_for_zip.csv', 'temporary_file2_for_zip.csv', 'test.csv', 'test1.txt', 'test2.txt', 'tmdb_5000_movies.csv']
이 메소드는 튜플을 허용한다는 것을 기억하십시오. 검색할 선택 목록이 있는 경우 이를 튜플로 변환해야 합니다.
import os # list with choices patters = ['.csv','.txt'] # get the file names filenames = os.listdir('.') # Let us first check if there are files any(name.endswith(patters) for name in filenames)
출력
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) in 8 9 # Let us first check if there are files ---> 10 any(name.endswith(patters) for name in filenames) in (.0) 8 9 # Let us first check if there are files ---> 10 any(name.endswith(patters) for name in filenames) TypeError: endswith first arg must be str or a tuple of str, not list
위의 명령은 오류를 반환하므로 목록을 튜플로 변환해야 합니다.
예시
# Let us first check if there are files any(name.endswith(tuple(patters)) for name in filenames)
출력
True
마찬가지로 파일 이름을 얻으려면 목록을 튜플로 변환해야 합니다.
예시
[name for name in filenames if name.endswith(tuple(patters)) ]
출력
['file1.csv', 'HRDataset.csv', 'Input.csv', 'input.txt', 'input_copy.txt', 'movies_data.csv', 'my_html_data_to_csv.csv', 'temporary_file1_for_zip.csv', 'temporary_file2_for_zip.csv', 'test.csv', 'test1.txt', 'test2.txt', 'tmdb_5000_movies.csv']
마지막으로, startswith() 및 endswith() 메서드는 일반적인 데이터 축소와 같은 다른 작업과 결합될 때 멋지게 보입니다. 예:
예시
if any(name.endswith(tuple(patters)) for name in filenames): <perform the logic here>