NLTK 토크 나이저를 사용하여 구두점을 제거하는 방법은 무엇입니까?
방금 NLTK를 사용하기 시작했는데 텍스트에서 단어 목록을 얻는 방법을 잘 모르겠습니다. 을 사용하면 nltk.word_tokenize()
단어 목록과 구두점을 얻습니다. 대신 단어 만 필요합니다. 구두점을 제거하려면 어떻게해야합니까? 또한 word_tokenize
여러 문장에서 작동하지 않습니다. 점이 마지막 단어에 추가됩니다.
nltk가 여기에서 제공하는 다른 토큰 화 옵션을 살펴 보십시오 . 예를 들어 일련의 영숫자 문자를 토큰으로 선택하고 나머지는 모두 삭제하는 토크 나이저를 정의 할 수 있습니다.
from nltk.tokenize import RegexpTokenizer
tokenizer = RegexpTokenizer(r'\w+')
tokenizer.tokenize('Eighty-seven miles to go, yet. Onward!')
산출:
['Eighty', 'seven', 'miles', 'to', 'go', 'yet', 'Onward']
구두점을 제거하기 위해 NLTK가 필요하지 않습니다. 간단한 파이썬으로 제거 할 수 있습니다. 문자열의 경우 :
import string
s = '... some string with punctuation ...'
s = s.translate(None, string.punctuation)
또는 유니 코드의 경우 :
import string
translate_table = dict((ord(char), None) for char in string.punctuation)
s.translate(translate_table)
그런 다음 토크 나이저에서이 문자열을 사용합니다.
PS 문자열 모듈에는 제거 할 수있는 다른 요소 세트 (예 : 숫자)가 있습니다.
아래 코드는 모든 문장 부호와 알파벳이 아닌 문자를 제거합니다. 그들의 책에서 복사했습니다.
http://www.nltk.org/book/ch01.html
import nltk
s = "I can't do this now, because I'm so tired. Please give me some time. @ sd 4 232"
words = nltk.word_tokenize(s)
words=[word.lower() for word in words if word.isalpha()]
print(words)
산출
['i', 'ca', 'do', 'this', 'now', 'because', 'i', 'so', 'tired', 'please', 'give', 'me', 'some', 'time', 'sd']
주석에서 알 수 있듯이 word_tokenize ()는 단일 문장에서만 작동하기 때문에 sent_tokenize ()로 시작합니다. filter ()를 사용하여 구두점을 필터링 할 수 있습니다. 그리고 만약 당신이 유니 코드 문자열을 가지고 있다면 그것이 유니 코드 객체인지 확인하십시오 ( 'utf-8'과 같은 인코딩으로 인코딩 된 'str'이 아님).
from nltk.tokenize import word_tokenize, sent_tokenize
text = '''It is a blue, small, and extraordinary ball. Like no other'''
tokens = [word for sent in sent_tokenize(text) for word in word_tokenize(sent)]
print filter(lambda word: word not in ',-', tokens)
방금 다음 코드를 사용하여 모든 구두점을 제거했습니다.
tokens = nltk.wordpunct_tokenize(raw)
type(tokens)
text = nltk.Text(tokens)
type(text)
words = [w.lower() for w in text if w.isalpha()]
일종의 정규식 일치가 필요하다고 생각합니다 (다음 코드는 Python 3에 있습니다).
import string
import re
import nltk
s = "I can't do this now, because I'm so tired. Please give me some time."
l = nltk.word_tokenize(s)
ll = [x for x in l if not re.fullmatch('[' + string.punctuation + ']+', x)]
print(l)
print(ll)
산출:
['I', 'ca', "n't", 'do', 'this', 'now', ',', 'because', 'I', "'m", 'so', 'tired', '.', 'Please', 'give', 'me', 'some', 'time', '.']
['I', 'ca', "n't", 'do', 'this', 'now', 'because', 'I', "'m", 'so', 'tired', 'Please', 'give', 'me', 'some', 'time']
Should work well in most cases since it removes punctuation while preserving tokens like "n't", which can't be obtained from regex tokenizers such as wordpunct_tokenize
.
I use this code to remove punctuation:
import nltk
def getTerms(sentences):
tokens = nltk.word_tokenize(sentences)
words = [w.lower() for w in tokens if w.isalnum()]
print tokens
print words
getTerms("hh, hh3h. wo shi 2 4 A . fdffdf. A&&B ")
And If you want to check whether a token is a valid English word or not, you may need PyEnchant
Tutorial:
import enchant
d = enchant.Dict("en_US")
d.check("Hello")
d.check("Helo")
d.suggest("Helo")
Remove punctuaion(It will remove . as well as part of punctuation handling using below code)
tbl = dict.fromkeys(i for i in range(sys.maxunicode) if unicodedata.category(chr(i)).startswith('P'))
text_string = text_string.translate(tbl) #text_string don't have punctuation
w = word_tokenize(text_string) #now tokenize the string
Sample Input/Output:
direct flat in oberoi esquire. 3 bhk 2195 saleable 1330 carpet. rate of 14500 final plus 1% floor rise. tax approx 9% only. flat cost with parking 3.89 cr plus taxes plus possession charger. middle floor. north door. arey and oberoi woods facing. 53% paymemt due. 1% transfer charge with buyer. total cost around 4.20 cr approx plus possession charges. rahul soni
['direct', 'flat', 'oberoi', 'esquire', '3', 'bhk', '2195', 'saleable', '1330', 'carpet', 'rate', '14500', 'final', 'plus', '1', 'floor', 'rise', 'tax', 'approx', '9', 'flat', 'cost', 'parking', '389', 'cr', 'plus', 'taxes', 'plus', 'possession', 'charger', 'middle', 'floor', 'north', 'door', 'arey', 'oberoi', 'woods', 'facing', '53', 'paymemt', 'due', '1', 'transfer', 'charge', 'buyer', 'total', 'cost', 'around', '420', 'cr', 'approx', 'plus', 'possession', 'charges', 'rahul', 'soni']
Sincerely asking, what is a word? If your assumption is that a word consists of alphabetic characters only, you are wrong since words such as can't
will be destroyed into pieces (such as can
and t
) if you remove punctuation before tokenisation, which is very likely to affect your program negatively.
Hence the solution is to tokenise and then remove punctuation tokens.
import string
from nltk.tokenize import word_tokenize
tokens = word_tokenize("I'm a southern salesman.")
# ['I', "'m", 'a', 'southern', 'salesman', '.']
tokens = list(filter(lambda token: token not in string.punctuation, tokens))
# ['I', "'m", 'a', 'southern', 'salesman']
...and then if you wish, you can replace certain tokens such as 'm
with am
.
Just adding to the solution by @rmalouf, this will not include any numbers because \w+ is equivalent to [a-zA-Z0-9_]
from nltk.tokenize import RegexpTokenizer
tokenizer = RegexpTokenizer(r'[a-zA-Z]')
tokenizer.tokenize('Eighty-seven miles to go, yet. Onward!')
참고URL : https://stackoverflow.com/questions/15547409/how-to-get-rid-of-punctuation-using-nltk-tokenizer
'IT story' 카테고리의 다른 글
Android Studio-ADB 오류-“… 기기가 승인되지 않았습니다. (0) | 2020.08.07 |
---|---|
터미널의 문자 인코딩을 얻는 방법 (0) | 2020.08.07 |
matplotlib 서브 플롯에 대한 공통 xlabel / ylabel (0) | 2020.08.07 |
Chrome에서 스크롤 막대가 페이지 너비에 추가되는 것을 방지 (0) | 2020.08.07 |
adb가 비 시장 APK를 업데이트합니까? (0) | 2020.08.07 |