如何将下面的双字母组合成一个字符串?
_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/