2017-10-16 20 views
1

lemmatizerを使用して文字列を前処理して、句読点と数字を削除しようとしています。私はこれを行うには、以下のコードを使用しています。エラーは出ませんが、テキストは適切に前処理されていません。ストップワードのみが削除されますが、リーマタイミングは機能せず、句読点や数字も残ります。Python:前処理テキスト

from nltk.stem import WordNetLemmatizer 
import string 
import nltk 
tweets = "This is a beautiful day16~. I am; working on an exercise45.^^^45 text34." 
lemmatizer = WordNetLemmatizer() 
tweets = lemmatizer.lemmatize(tweets) 
data=[] 
stop_words = set(nltk.corpus.stopwords.words('english')) 
words = nltk.word_tokenize(tweets) 
words = [i for i in words if i not in stop_words] 
data.append(' '.join(words)) 
corpus = " ".join(str(x) for x in data) 
p = string.punctuation 
d = string.digits 
table = str.maketrans(p, len(p) * " ") 
corpus.translate(table) 
table = str.maketrans(d, len(d) * " ") 
corpus.translate(table) 
print(corpus) 

私が手に最終的な出力は次のようになります。

This beautiful day16~ . I ; working exercise45.^^^45 text34 . 

と期待される出力は次のようになります。

This beautiful day I work exercise text 
+0

。 –

+0

この提案をありがとうございます。しかし、私が期待しているように上記のコードは動作しません。以前は同じコードを使用していましたが、うまくいきませんでしたが、今回はうまくいかない理由はわかりません。 – Alex

答えて

0

いいえ、あなたの現在のアプローチは動作しません、あなたがそうでなければ、これらの機能は、文として、あなたの文字列を解釈するために知ることができません、lemmatizer /ステマに時間で一つの単語を渡す必要がありますので、(彼らは単語を期待する)。また

import re 

__stop_words = set(nltk.corpus.stopwords.words('english')) 

def clean(tweet): 
    cleaned_tweet = re.sub(r'([^\w\s]|\d)+', '', tweets.lower()) 
    return ' '.join([lemmatizer.lemmatize(i, 'v') 
       for i in cleaned_tweet.split() if i not in __stop_words]) 

、あなたはlemmatisationとしてではなく、コンテキストなしで同じことを行いPorterStemmerを、使用することができます。

from nltk.stem.porter import PorterStemmer 
stemmer = PorterStemmer() 

そして、このようステマーを呼び出す:私はlemmatizerを呼び出す前に、ノイズを取り除くために正規表現を使用したい

stemmer.stem(i) 
+0

ねえ、私のテキストがデータフレームの列である場合、テキストをどのように前処理することができるか教えてください。私はすべての句読点、数字、およびテキストの字句を削除し、データフレームの1列のすべての行からストップワードを削除したいと考えています。 – Alex

+0

@Ritikaは関数を定義し、それをdf.applyに渡します。 –

+0

ありがとう:) – Alex

1

私は前に、これはあなたが探しているものだと思いますが、これを行いますコメント欄に記されているように、字句解析ツールを呼び出すことにしました。

>>>import re 
>>>s = "This is a beautiful day16~. I am; working on an exercise45.^^^45text34." 
>>>s = re.sub(r'[^A-Za-z ]', '', s) 
This is a beautiful day I am working on an exercise text