【问题标题】:how to remove punctuation and stop words using python如何使用python删除标点符号和停用词
【发布时间】:2020-07-07 09:26:14
【问题描述】:

我有一个必须删除 标点符号停用词 的 python 函数,但是当我打印结果时它不会删除它。

我的函数中的错误在哪里?

代码:

    from nltk.corpus import stopwords
    from string import punctuation
        ppt = '''...!@#$%^&*(){}[]|._-`/?:;"'\,~12345678876543''' 
    
        def text_process(raw_text):
            '''
            parameters:
            =========
            raw_text: text as input
            functions:
            ==========
            - remove all punctuation
            - remove all stop words
            - return a list of the cleaned text
        
            '''
            #check characters to see if they are in punctuation
            nopunc = [char for char in list(raw_text)if char not in ppt]
          
            # join the characters again to form the string
            nopunc = "".join(nopunc)
            
            #now just remove ant stopwords
            return [word for word in nopunc.lower().split() if word.lower() not in stopwords.words("english")]

def_test_twtr_preds["tokens"] = def_test_twtr_preds["processed_TEXT"].apply(text_process)


#get most common words in  dataset
all_words = []
for line in list(def_test_twtr_preds["processed_TEXT"]):
    words = line.split()
    for word in words:
        all_words.append(word.lower())
print("Most common words:\n{}".format(Counter(all_words).most_common(10)))

当我显示数据集中存在的最常见单词的结果是:

Most common words:
[('the', 281), ('and', 103), ('words', 81), ('…', 70), ('are', 61), ('word', 57), ('for', 55), ('you', 48), ('this', 40), ('.', 34)]

【问题讨论】:

  • 请提供minimal reproducible example。在您的示例中,至少缺少停用词的定义(或导入)。
  • 标题 how to remove punctuation and stop words using python and regex 对我来说似乎有些误导 - 你在这里不使用 regex(re 模块)。
  • 我的错误,但我的问题是如何使用正则表达式或我展示的函数删除它。我会换个问题
  • 你使用nltk,为什么不使用它的内置函数呢?
  • @ipramusinto 你的意思是我正在使用 nltk 的包和功能。 word for word in nopunc.lower().split() if word.lower() not in stopwords.words("english") 我正在使用包 nltk.corpus 作为停用词我的函数中的错误在哪里??

标签: python stop-words punctuation


【解决方案1】:

注意list('your text') 将导致['y','o','u','r','t','e','x','t'] 不是 ['your', 'text']

您可以使用删除标点符号 nopunc = [w for w in text_raw.split() if w.isalpha()]

但是,上面的代码也会删除I'm fine 中的单词I'm。所以如果你想得到['I','m','fine'],你可以使用下面的代码:

tokenizer = nltk.RegexpTokenizer(r"\w+")
nopunc = tokenizer.tokenize(raw_text)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-04
    • 1970-01-01
    • 2020-11-06
    • 2019-09-16
    • 1970-01-01
    • 1970-01-01
    • 2011-07-29
    • 1970-01-01
    相关资源
    最近更新 更多