문자열에서 단어 수를 가져오는 방법을 소개합니다.
1. split()을 이용한 방법
string.split()
은 문자열을 공백으로 분리하고 분리된 문자열을 리스트로 리턴합니다. 리턴된 리스트의 길이가 단어의 개수가 됩니다.
str = "Hello, world. This is an example."
result = str.split()
word_cnt = len(result)
print(result)
print(word_cnt)
Output:
['Hello,', 'world.', 'This', 'is', 'an', 'example.']
6
2. 정규표현식을 이용한 방법
re.findall(pattern, string)
은 string에서 pattern과 일치하는 문자열을 찾아서 리스트로 리턴합니다.
re.findall(r'\w+', str)
를 이용하여 단어의 개수를 가져올 수 있습니다.
\w
패턴은 word를 의미하며 알파벳, 숫자,_
중의 한 문자를 의미\w+
에서+
는 앞의 패턴이 1회 이상 반복되는 문자들을 의미, 즉,\w+
는 1개 이상의 word들을 의미
import re
str = "Hello, world. This is an example."
result = re.findall(r'\w+', str)
word_cnt = len(result)
print(result)
print(word_cnt)
Output:
['Hello', 'world', 'This', 'is', 'an', 'example']
6
Loading script...
Related Posts
- Python 에러 해결, 'conda' 용어가 cmdlet, 함수, 스크립트 ... 인식되지 않습니다.
- Python 에러 해결, AttributeError: module 'jwt' has no attribute 'encode'
- Python - assert 사용 방법
- Python - Counter로 Collection 개수 세기
- Python - enumerate(), for/index 예제
- Python - count(), len() 함수
- Python - join() 함수, 문자열 합치기
- Python - 줄바꿈 입력 방법
- Python - 딕셔너리를 JSON으로 변환
- Python - JSON을 딕셔너리로 변환
- Python - 딕셔너리 Index로 접근/순회 방법
- Python - 딕셔너 리 CSV 파일 쓰기/읽기
- Python - 딕셔너리 update() 함수
- Python - JSON 예쁘게(pretty), 정렬하여 출력
- Python - CSV 파일을 JSON 파일로 변환
- Python - CSV 파일을 리스트로 변환
- Python - List를 Set로 변환
- Python - Set을 List로 변환
- Python - 텍스트 파일 이어서 쓰기
- Python - 파일 끝 찾기
- Python - 파일 수정 시간, 생성 시간 확인