【问题标题】:Is there a way of removing all the words in the text that are not in other text?有没有办法删除文本中不在其他文本中的所有单词?
【发布时间】:2019-04-16 04:29:21
【问题描述】:

我有一份包含许多评论的文档。我正在使用 TfidfVectorizer 创建一个词袋 BW。我想要做的是:我只想在 BW 中使用其他文档 D 中的单词。

文档 D 是一个带有肯定词的文档。我正在使用这种积极的方式来改进我的模型。我的意思是:我只想计算积极的词。

有没有办法做到这一点?

谢谢

我创建了一段代码来完成这项工作,如下所示: train_x 是带有评论的熊猫数据框。

pos_file = open("positive-words.txt")
neg_file = open("negative-words.txt")

#creating arrays based on the files
for ln in pos_file:
    pos_words.append(ln.strip())
for ln in neg_file:
    neg_words.append(ln.strip())

#adding all the positive and negative words together
sentiment_words.append(pos_words)
sentiment_words.append(neg_words)

pos_file.close()
neg_file.close()

#filtering all the words that are not in the sentiment array
filtered_res =[]
for r in train_x:
    keep = []
    parts = r.split()
    for p in parts:
        if p in pos_words:
            keep.append(p)
    #turning the Review array back to text again
    filtered_res.append(" ".join(keep))

train_x = filtered_res

虽然我能够满足我的需求,但我知道代码并不是最好的。另外,我试图在 python 中找到一个标准函数来做到这一点

PS:Python 有这么多的特性,我总是问它可以在不使用我使用的大量代码的情况下做什么

【问题讨论】:

  • 是的,如果您可以展示一些示例并展示您在这里想要实现的具体目标,您可以这样做?
  • 嘿!感谢您的回答。我编辑我的问题,添加我创建的代码来解决我的问题。我想要的基本上是:从评论文本中删除所有不必要的单词,只保留一个重要的(正面和负面),然后从那里创建我的模型。

标签: python scikit-learn tf-idf tfidfvectorizer


【解决方案1】:

这里有一个更优化的版本(因为

  1. 它不会在循环中的 pos_words 中进行线性搜索 p
  2. 它对循环进行矢量化(更符合 Python 风格)
  3. 不是为每个 r 保留一个列表,而是有生成器版本

import re

pos_words_set = set (pos_words)

def filter (r):
    keep = []
    # use [A-Za-z] to avoid numbers
    for p in re.finditer(r"[A-Za-z0-9]+", string):
        if p in pos_words_set:
            keep.append(p)
    return " ".join(keep)

train_x = train_x.apply(lambda x : filter(x), axis=1)

【讨论】:

    猜你喜欢
    • 2023-03-08
    • 1970-01-01
    • 2022-10-07
    • 1970-01-01
    • 2021-01-25
    • 1970-01-01
    • 1970-01-01
    • 2020-09-21
    • 1970-01-01
    相关资源
    最近更新 更多