如何分隔大数据集中在一起的单词

数据挖掘 熊猫 数据 数据清理 大数据 文本
2022-02-17 15:43:59

在推特数据中,我遇到了像“抵制熊”这样粘在一起的词,我希望它们成为“抵制”“熊”“人”

我试过了,但这很慢

def split(sentence, word_to_index):
# words to index dictionary of valid words
    sentence_words = sentence.split()
    lst12=[] 
    for w in sentence_words:
            lst=[] 
            ws=w[:]
            # Set the (i,j)th entry of X_indices to the index of the correct word.
            while True:
                for wd in lst:
                    ws = ws.replace(wd,"")
                if ws=="":
                    lst=" ".join(lst)
                    lst12.append(lst)
                    break
                wrdind = ws[:]
                for kl in range(len(ws)):
                    try:
                        word_to_index[wrdind]
                        lst.append(wrdind)
                        break     

                    except KeyError:
                            wrdind = wrdind[:len(wrdind)-1]
                            continue
   return " ".join(lst12)  
```
1个回答

这通常称为“断字”问题。方法有很多种,最常见的使用动态规划或尝试。如果候选者可以拆分整个字符串,您可以递归地尝试候选者并保留候选者。

这是一个版本(受此答案的启发):

from functools import lru_cache

@lru_cache(None)
def wordbreak(string):
    if len(string) < 1:
        return " "
    else:
        for i in range(len(string)):
            substring = string[:i+1]
            if substring in valid_words:
                remaining_split = wordbreak(string[i+1:])
                if len(remaining_split) > 0:
                    return substring + " " + remaining_split
                else:
                    return ""
            if (i == len(string) - 1) and (substring not in valid_words):
                return ""

valid_words = {'man', 'boycott', 'bears'}                                            
assert wordbreak('boycottbears') == 'boycott bears'
assert not wordbreak('abc')

然而,对于 Twitter 数据来说,创建一个完整的有效词集合是不可能的,因为总是有新词。