如何使用NLTK从大文本语料库中仅提取英语单词



我想从文本语料库中删除所有非字典英语单词。我已经删除了停止词,标记并计算数据。我需要仅提取英文单词并将其附加回数据框。

data['Clean_addr'] = data['Adj_Addr'].apply(lambda x: ' '.join([item.lower() for item in x.split()]))
        data['Clean_addr']=data['Clean_addr'].apply(lambda x:"".join([item.lower() for item in x if  not  item.isdigit()]))
        data['Clean_addr']=data['Clean_addr'].apply(lambda x:"".join([item.lower() for item in x if item not in string.punctuation]))
        data['Clean_addr'] = data['Clean_addr'].apply(lambda x: ' '.join([item.lower() for item in x.split() if item not in (new_stop_words)]))
        cv = CountVectorizer( max_features = 200,analyzer='word')
        cv_addr = cv.fit_transform(data.pop('Clean_addr'))

我正在使用

的文件示例转储

https://www.dropbox.com/s/allhfdxni0kfyn6/test.csv?dl=0

首先示意文本语料库后,您可以 stem> stem 单词tokens

import nltk
from nltk.stem.snowball import SnowballStemmer
stemmer = SnowballStemmer(language="english")

SnowballStemmer

  • 是执行词干的算法
    • 茎只是将一个单词倒入其根部的过程。
  • 通过参数"英语"和emsp;↦  Porter2 Stemming算法
    • 更确切地说,这个"英语"参数 ↦ stem.snowball.EnglishStemmer
    • porter2 stemmer被认为比原始的porter蒸馏器更好)

 

stems = [stemmer.stem(t) for t in tokenized]  

上面,我定义了一个列表理解,该列表执行如下:

  1. 列表理解循环我们的令牌输入list 令牌
    • 令牌化也可以是其他任何其他峰值输入实例)
  2. 列表理解的操作是使用SnowballStemmer实例 stemmer
  3. 在每个令牌化词上执行.stem方法
  4. 列表理解然后收集英语词干集
    • 即,它是一个应该收集 stemed英语单词令牌
    • 的列表

 

警告: 列表理解可能可以想像包括某些相同的在其他语言中呈现的单词,因为英语会从英语中判断,因为 porter2 会错误地认为它们是英语单词

直至本质

我的需求非常相似。您的问题出现在我的搜索中。觉得我需要进一步寻找,我找到了这个。我针对我的特定需求进行了一些修改(只有大量的技术数据表中的英语单词=无数字或测试标准或值或单位等)。经过其他方法的痛苦,下面有效。我希望这对您和其他人来说都是一个好的发射点。

import nltk
from nltk.corpus import stopwords
words = set(nltk.corpus.words.words())
stop_words = stopwords.words('english')

file_name = 'Full path to your file'
with open(file_name, 'r') as f:
    text = f.read()
    text = text.replace('n', ' ')
new_text = " ".join(w for w in nltk.wordpunct_tokenize(text)
                    if w.lower() in words
                    and w.lower() not in stop_words
                    and len(w.lower()) > 1)
print(new_text)

我使用了Pyenchant库来做到这一点。

import enchant
d = enchant.Dict("en_US")
def get_eng_words(data):
    eng =[]
    for sample in tqdm(data):
        sentence=''
        word_tokens = nltk.word_tokenize(sample)
            for word in word_tokens:
            if(d.check(word)):
                if(sentence ==''):
                    sentence = sentence + word
                else:
                    sentence = sentence +" "+ word
        print(sentence)
        eng.append(sentence)
    return eng

要保存它,只需做到这一点!

sentences=get_eng_words(df['column'])
df['column']=pd.DataFrame(sentences)

希望它能帮助任何人!

最新更新