Python字典替换键中的空格

翠黄

我有一个字符串和一个字典,我必须替换该文本中每次出现的dict键。

text = 'I have a smartphone and a Smart TV'
dict = {
    'smartphone': 'toy',
    'smart tv': 'junk'
}

如果键中没有空格,我将把文本分解成单词,然后与dict逐一比较看起来花了O(n)但是现在钥匙里面有空间,所以事情变得更加复杂。请建议我这样做的好方法,并请注意密钥可能与文本的大小写不匹配。

更新

我已经想到了这种解决方案,但是效率不高。O(m * n)或更多...

for k,v in dict.iteritems():
    text = text.replace(k,v) #or regex...
翠黄

如果文字中的关键字彼此之间不太接近(关键字其他关键字),我们可以这样做。把O(n)交给我>“ <

def dict_replace(dictionary, text, strip_chars=None, replace_func=None):
    """
        Replace word or word phrase in text with keyword in dictionary.

        Arguments:
            dictionary: dict with key:value, key should be in lower case
            text: string to replace
            strip_chars: string contain character to be strip out of each word
            replace_func: function if exist will transform final replacement.
                          Must have 2 params as key and value

        Return:
            string

        Example:
            my_dict = {
                "hello": "hallo",
                "hallo": "hello",    # Only one pass, don't worry
                "smart tv": "http://google.com?q=smart+tv"
            }
            dict_replace(my_dict, "hello google smart tv",
                         replace_func=lambda k,v: '[%s](%s)'%(k,v))
    """

    # First break word phrase in dictionary into single word
    dictionary = dictionary.copy()
    for key in dictionary.keys():
        if ' ' in key:
            key_parts = key.split()
            for part in key_parts:
                # Mark single word with False
                if part not in dictionary:
                    dictionary[part] = False

    # Break text into words and compare one by one
    result = []
    words = text.split()
    words.append('')
    last_match = ''     # Last keyword (lower) match
    original = ''       # Last match in original
    for word in words:
        key_word = word.lower().strip(strip_chars) if \
                   strip_chars is not None else word.lower()
        if key_word in dictionary:
            last_match = last_match + ' ' + key_word if \
                         last_match != '' else key_word
            original = original + ' ' + word if \
                       original != '' else word
        else:
            if last_match != '':
                # If match whole word
                if last_match in dictionary and dictionary[last_match] != False:
                    if replace_func is not None:
                        result.append(replace_func(original, dictionary[last_match]))
                    else:
                        result.append(dictionary[last_match])
                else:
                    # Only match partial of keyword
                    match_parts = last_match.split(' ')
                    match_original = original.split(' ')
                    for i in xrange(0, len(match_parts)):
                        if match_parts[i] in dictionary and \
                           dictionary[match_parts[i]] != False:
                            if replace_func is not None:
                                result.append(replace_func(match_original[i], dictionary[match_parts[i]]))
                            else:
                                result.append(dictionary[match_parts[i]])
            result.append(word)
            last_match = ''
            original = ''

    return ' '.join(result)

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

Python用字典中的值替换键

来自分类Dev

如何从Python字典中的键中删除尾随空格?

来自分类Dev

替换JSON键中的空格

来自分类Dev

替换JSON键中的空格

来自分类Dev

在python中替换字典中的冗余键和值

来自分类Dev

Python - 根据列表替换嵌套字典中的所有键

来自分类Dev

从字典键/值对中删除空格

来自分类Dev

在Python中替换字典时,是否可以引用字典从键中获取值?

来自分类Dev

如果字典键中存在,Python 将列表中逗号分隔的单词替换为字典值

来自分类Dev

迭代下替换字典键的Python行为

来自分类Dev

根据其值替换字典中的键

来自分类Dev

如何在Python中用字典中的键替换列表中的项目

来自分类Dev

在替换重复键时选择在字典中替换哪个值?

来自分类Dev

在替换重复键时选择在字典中替换哪个值?

来自分类Dev

如何使用替换替换嵌套字典中的键

来自分类Dev

用字典中的缩写键替换“全名”键

来自分类Dev

用字典中的缩写键替换“全名”键

来自分类Dev

如何用列表中的可用键替换字典键?

来自分类Dev

在python字典中替换无

来自分类Dev

替换Python字典中的值

来自分类Dev

在python中替换字典的值

来自分类Dev

替换 Python 字典中的条目

来自分类Dev

字典中的条件键-python

来自分类Dev

python中的字典键是RegExp

来自分类Dev

字典中的python相似键

来自分类Dev

python字典中的重复键

来自分类Dev

python-将键的值替换为与同一字典中的不同键对应的值

来自分类Dev

如何使用Javascript动态替换JSON对象键中的空格?

来自分类Dev

多模式替换以及python中的空格