작은 샘플 텍스트를 구분자가없고 각 문장 끝에 공백이없는 문장 목록으로 분할하려고합니다.
샘플 텍스트 :
두 번째 르네상스가 처음 보이면 지루해 보일 수 있습니다. 적어도 두 번보고 확실히 2 부를보십시오. 그러면 행렬에 대한 시야가 달라집니다. 인류는 전쟁을 시작한 사람들입니까? AI가 나쁜 것입니까?
이것으로 (원하는 출력) :
['The first time you see The Second Renaissance it may look boring', 'Look at it at least twice and definitely watch part 2', 'It will change your view of the matrix', 'Are the human people the ones who started the war', 'Is AI a bad thing']
내 코드는 현재 :
def sent_tokenize(text):
sentences = re.split(r"[.!?]", text)
sentences = [sent.strip(" ") for sent in sentences]
return sentences
그러나이 출력 (현재 출력) :
['The first time you see The Second Renaissance it may look boring', 'Look at it at least twice and definitely watch part 2', 'It will change your view of the matrix', 'Are the human people the ones who started the war', 'Is AI a bad thing', '']
끝에 여분의 ''을 통지하십시오.
현재 출력이 끝날 때 추가 항목을 제거하는 방법에 대한 아이디어가 있습니까?
-
답변 # 1
-
답변 # 2
['The first time you see The Second Renaissance it may look boring', 'Look at it at least twice and definitely watch part 2', 'It will change your view of the matrix', 'Are the human people the ones who started the war', 'Is AI a bad thing']
nltk
NLP 사업을하고 있다면
sent_tokenize
를 강력히 추천합니다sent_tokenize
에서 패키지.nltk
정규식보다 훨씬 강력하고 작업을 수행 할 수있는 많은 옵션을 제공합니다. 자세한 정보는 공식 문서를 참조하십시오.
후행 구분 기호가 까다 롭다면
>>> from nltk.tokenize import sent_tokenize >>> sent_tokenize(text) [ 'The first time you see The Second Renaissance it may look boring.', 'Look at it at least twice and definitely watch part 2.', 'It will change your view of the matrix.', 'Are the human people the ones who started the war?', 'Is AI a bad thing?' ]
를 사용할 수 있습니다. 약간 다른 패턴으로 :nltk.tokenize.RegexpTokenizer
>>> from nltk.tokenize import RegexpTokenizer >>> tokenizer = RegexpTokenizer(r'[^.?!]+') >>> list(map(str.strip, tokenizer.tokenize(text))) [ 'The first time you see The Second Renaissance it may look boring', 'Look at it at least twice and definitely watch part 2', 'It will change your view of the matrix', 'Are the human people the ones who started the war', 'Is AI a bad thing' ]
만약필요하다면
re.split
를 사용하십시오 그런 다음 제외 미리보기를 추가하여 패턴을 수정해야합니다-regex
추가 된
>>> list(map(str.strip, re.split(r"[.!?](?!$)", text))) [ 'The first time you see The Second Renaissance it may look boring', 'Look at it at least twice and definitely watch part 2', 'It will change your view of the matrix', 'Are the human people the ones who started the war', 'Is AI a bad thing?' ]
줄 끝에 아직 도달하지 않은 경우에만 분할하도록 지정합니다. 불행히도, 나는 마지막 문장의 후행 구분 기호가(?!$)
와 같은 것을하지 않고 합리적으로 제거 될 수 있는지 확실하지 않습니다. . -
답변 # 3
필터를 사용하여 빈 요소를 제거 할 수 있습니다
예 :
result[-1] = result[-1][:-1]
-
답변 # 4
import re text = """The first time you see The Second Renaissance it may look boring. Look at it at least twice and definitely watch part 2. It will change your view of the matrix. Are the human people the ones who started the war? Is AI a bad thing?""" def sent_tokenize(text): sentences = re.split(r"[.!?]", text) sentences = [sent.strip(" ") for sent in sentences] return filter(None, sentences) print sent_tokenize(text)
단락을 나누기 전에 먼저 단락을 만들거나 결과에서 빈 문자열을 필터링하십시오.strip
관련 자료
- 파이썬에서 정규식을 사용하여 패턴 제외
- 파이썬에서 정규식 (refindall)을 사용하여 텍스트에서 15 자리 문자열 추출
- Python argparse를 사용하여 명령 줄 문제를 해결하는 방법은 무엇입니까?
- 정규식은 파이썬에서 정규식 변수로 대체 할 수 없습니다
- 이 정규식은 Python의 문자열 메서드로만 달성 할 수 있습니까?
- 그룹의 각 문자를 대체하는 Python Regex
- C #을 사용한 사용자 입력 후 Python 출력을 C #에 표시
- json - 파이썬을 사용하여 사전 객체를 어떻게 삭제할 수 있습니까?
- python (python -m httpserver)을 사용하여 로컬 서버에서 html 파일을 열려면 어떻게해야합니까?
- python - regex를 사용하여 "사용자"다음에 모든 사용자 가져 오기 -
- regex r - 벡터 문자열을 사용하여 텍스트에서 문자열 제거
- Python Flask에서 CSS 사용
- Google 스프레드 시트에서 정규식을 사용하여 JSON 구문 분석
- 명령 줄을 사용하지 않고 파이썬 파일을 실행할 수있는 방법이 있습니까?
- 밑줄을 포함한 모든 선행 숫자를 제거하는 Python 정규식
- pysocks python을 사용하여 https reuqest를 보내는 방법
- embedded - python을 사용하는 trace32 - t32_readmemoryobj 함수에서 반환 데이터를 해석하는 방법
- For 루프, 논리 오류를 사용하여 파이썬에서 정수 반복
- flux - Python을 사용하여 Influxdbv2 데이터를 쿼리 할 수없는 이유는 무엇입니까?
- Python Regex 긴 하이픈과 그 앞에있는 문자
- 파이썬에서 정규식 (refindall)을 사용하여 텍스트에서 15 자리 문자열 추출
- python - split을 사용하여 json에서 정수 추출
- python - 문자열 목록에서 키워드를 필터링하려면 어떻게해야합니까?
- python - 문자열에서 여러 문자를 바꾸는 가장 좋은 방법
- python - 특정 패턴에 대한 정규식
- python - 문자열의 정규식 다중 하위 문자열
- python - pandas strextract 메서드가 내 목록에서 더 많은 일치 항목을 반환하는 방법은 무엇입니까?
- Regex - 정규식 - 하이픈 뒤의 텍스트를 python의 사전으로 추출
- regex - 문자열에서 패턴을 검색하고 파이썬을 사용하여 문자열의 특정 부분 만 출력하려면 어떻게해야합니까?
- python - pandas 데이터 프레임에서 열 순서 지정 및 이름 바꾸기 - 우아한 솔루션 가능?
와이즈 비즈
이 작업을 수행하면 제거 할 수 있습니다 :
또는 더 빠름 (ᴄᴏʟᴅsᴘᴇᴇᴅ)
출력 :