检测文本样本中的样板

数据挖掘 文本挖掘 数据清理 数据争吵
2022-03-09 15:50:17

我有一个非结构化文本的语料库,由于来自不同来源的串联,它具有我想删除的样板元数据。例如:

作者提供的描述:我的目标...

作者提供:我的目标...

我的目标...... 成绩单结束

我的目标……完,由 XYZ 公司赞助

我的目标...赞助:XYZ公司,保留所有权利,日期:10/21

可以假设该样板出现在每个样本的开头或结尾。有哪些可靠的方法可以从数据中解决这个问题?

1个回答

这可能会让你开始。短语长度由 range() 函数确定。基本上,这将标记并创建 n-gram。然后它计算每个令牌。在最后一行打印出在所有文档中具有高平均值的标记(经常出现在文档中)。

from sklearn.feature_extraction.text import CountVectorizer
import numpy as np
import nltk

text = """DESCRIPTION PROVIDED BY AUTHOR: The goal of my a...
Author provided: The goal of my b...
The goal of my c... END OF TRANSCRIPT
The goal of my d... END SPONSORED BY COMPANY XYZ
The goal of my e... SPONSORED: COMPANY XYZ All rights reserved date: 10/21
"""

def todocuments(lines):
    for line in lines:
        words = line.lower().split(' ')
        doc = ""
        for n in range(3, 6):
            ts = nltk.ngrams(words, n)
            for t in ts: doc = doc + " " + str.join('_', t) 
        yield doc

cv = CountVectorizer(min_df=.5)

fit = cv.fit_transform(todocuments(text.splitlines()))
vocab_idx = {b: a for a, b in cv.vocabulary_.items()}

means = fit.mean(axis=0)
arr = np.squeeze(np.asarray(means))
[vocab_idx[idx] for idx in np.where(arr > .95)[0]]
# ['goal_of_my', 'the_goal_of', 'the_goal_of_my']