python - 将 n-gram 合并或反转为单个字符串

标签 python n-gram

如何将下面的双字母组合成一个字符串?

_bigrams=['the school', 'school boy', 'boy is', 'is reading']
_split=(' '.join(_bigrams)).split()
_newstr=[]
_filter=[_newstr.append(x) for x in _split if x not in _newstr]
_newstr=' '.join(_newstr)
print _newstr

输出:'the school boy is reading'....它是所需的输出,但该方法太长且效率不高,因为我的数据量很大。其次,该方法不支持最终字符串中的重复单词,即 'the school boy is reading, is he?'。在这种情况下,最终字符串中只允许使用 'is' 之一。

关于如何使这项工作更好的任何建议?谢谢。

最佳答案

# Multi-for generator expression allows us to create a flat iterable of words
all_words = (word for bigram in _bigrams for word in bigram.split())

def no_runs_of_words(words):
    """Takes an iterable of words and returns one with any runs condensed."""
    prev_word = None
    for word in words:
        if word != prev_word:
            yield word
        prev_word = word

final_string = ' '.join(no_runs_of_words(all_words))

这利用了生成器延迟求值的优势,而不是将整组单词同时保存在内存中,直到生成一个最终字符串。

关于python - 将 n-gram 合并或反转为单个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22426159/

相关文章:

python - 从字符串生成 n-gram

python - 在 Pandas 数据框中形成单词的二元组

python - 如何使用分而治之的多线程?

python - 为 django 模型生成唯一的哈希值

python - 在 Python 中使用二进制,拆分数字

python - 在python nltk中查找trigram的条件概率

python - Django SItemap 索引 NoReverseMatch at/sitemap.xml

python - Docker hyperkit 进程 CPU 使用率变得疯狂。如何控制它?

java - 计算字符串的概率

nlp - Unigram 在语言识别方面比 Ngram 提供更好的结果