【问题标题】:How to replace a list of strings in a text where some of them are substrings of other in python?如何替换文本中的字符串列表,其中一些是python中其他字符串的子字符串?
【发布时间】:2016-08-25 14:48:16
【问题描述】:

我有一个包含一些我想标记的单词的文本,并且要标记的单词包含在一个列表中。问题是其中一些单词是其他单词的子字符串,但我想标记列表中最长的识别字符串。

例如,如果我的文本是“foo and bar is different from foo bar”。我的列表包含“foo”、“bar”和“foo bar”,结果应该是“[tag]foo[/tag] 和 [tag]bar[/tag] 不同于 [tag]foo bar[/tag] 。”

text = "foo and bar are different from foo bar."
words = ["foo", "bar", "foo bar"]

tagged = someFunction(text, words)

如果字符串 taggedText 的值为"<tag>foo</tag> and <tag>bar</tag> are different from <tag>foo bar</tag>.",那么 someFunction 的代码应该是什么?

【问题讨论】:

  • 你能提出你的一个想法吗?我会使用一个函数,按字符串的长度对words 的列表进行排序,然后循环遍历text,标记所有的积极因素,同时检查两个标记词是否已经存在由<tag></tag> 字符串圈出...

标签: python regex string substring


【解决方案1】:

实现此目的的一种简单方法是按长度以相反的顺序对words 进行排序,然后创建一个正则表达式word1|word2|...。由于重新引擎总是取第一个匹配项,因此将首先捕获较长的字符串。

import re

def tag_it(text, words):
    return re.sub(
            '|'.join(sorted(words, key=len, reverse=True)),
            lambda m: '<tag>' + m.group(0) + '</tag>',
            text)


text = "foo and bar are different from foo bar."
words = ["foo", "bar", "foo bar"]


print tag_it(text, words)

【讨论】:

    【解决方案2】:

    如果我正确理解了您的问题,那么这就是您正在寻找的东西:-

    text = "foo and bar are different from foo bar."
    words = ["foo", "bar", "foo bar"]
    
    add_tag = lambda var : "<tag>"+var+"</tag>"
    
    result = ''    # for final string
    for var in text.split():
        if var in words:
            tmp = add_tag(var)
        else:
            tmp = var
        result += " "+tmp
    
    print result    
    return result
    

    这里add_tag() 方法正在为您在someFunction 中查找的内容提供服务。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-21
      • 2023-03-19
      • 1970-01-01
      • 1970-01-01
      • 2023-01-30
      • 2021-11-20
      • 1970-01-01
      • 2021-12-19
      相关资源
      最近更新 更多