【问题标题】:How can I write a rule in spacy with pattern inside a pattern (nested pattern)如何在模式中使用模式(嵌套模式)编写规则
【发布时间】:2022-01-17 17:15:59
【问题描述】:

我想在 Spacy 中编写一个匹配文本的模式,然后可以选择文本右侧的所有括号(如果有的话)。

例如,对于以下文本,我将箭头“->”的左侧部分作为输入,并将箭头的右侧部分作为输出。

However, we found that This Example (TE (as explained above) other stuff) -> This Example (TE (as explained above) other stuff)

Here is another example This Example (TE (some text here)) -> This Example (TE (some text here))

Some random text and then This Example (TE) -> This Example (TE)

Then a final example This Example -> This Example

这些文本不固定,仅作为示例。

我希望得到与结尾一样多的起始括号(甚至可能没有括号模式)

我尝试了以下方法,但它不起作用。

patt_1 = [
    {"OP": "+", "LOWER": {"IN": ['this','example']}},
    {"OP": "*", "LOWER": {"IN":["("]}},
    {"OP": "*", "POS": {"IN":["ADJ", "PROPN", "NOUN", "CCONJ", "NUM", "ADV"]}},
    {"OP": "*", "LOWER": {"IN": [")"]}}
]

它只匹配第一个括号。由于我对长文本进行操作,如果末尾有右括号,我还想匹配一个短语而不是整个文档。

我想要类似下面的东西,但它不起作用......


patt_1 = [
{"OP": "+", "LOWER": {"IN":["("]}},
{"OP": "+", "POS": {"IN":["ADJ", "PROPN", "NOUN"]}},
{"OP": "+", "LOWER": {"IN": [")"]}}
]
patt_2 = [
{"OP": "+", "LOWER": {"IN":["("]}},
{"OP": "+", "POS": {"IN":["ADJ", "PROPN", "NOUN"]}},
{"OP": "+", "LOWER": {"IN":["("]}},
{"OP": "+", "POS": {"IN":["ADJ", "PROPN", "NOUN"]}},
{"OP": "+", "LOWER": {"IN": [")"]}},
{"OP": "+", "POS": {"IN":["ADJ", "PROPN", "NOUN"]}},
{"OP": "+", "LOWER": {"IN": [")"]}}
]

patt_3 = [
    {"OP": "+", "LOWER": {"IN": ['this','example']}},
    { "OP": "*", patt_1},
    { "OP": "*", patt_2}
]

感谢您的帮助

【问题讨论】:

    标签: python nested spacy rules


    【解决方案1】:

    如果所有文本都具有相同的模式,则可以使用正则表达式来识别正确的部分。

    import re
    
    text = "However, we found that This Example (TE (as explained above) other stuff)"
    cleaned_text = re.sub(r"However, we found that ", "", text).strip()
    print(cleaned_text) # Outputs "This Example (TE (as explained above) other stuff)"
    

    编辑(见 cmets):

    specific_phrase = "This Example"
    example_document = "However, we found that This Example (TE (as explained above) other stuff)"
    brackets_regex = r" \(.*\)"
    
    if re.search(specific_phrase, example_document) and re.search(brackets_regex, example_document):
        matched_pattern = specific_phrase + re.search(brackets_regex, example_document).group()
    print(matched_pattern) # Output: This Example (TE (as explained above) other stuff)
    

    然后可以将其放入一个函数中,然后循环遍历您的文档以处理它们。

    【讨论】:

    • 给定“->”表达式的左侧部分,我想获得“->”的右侧部分文本没有任何“->”。我刚刚添加了这些输入输出示例。
    • 道歉,但鉴于信息尚不清楚。鉴于信息,我已经编辑了我认为您正在寻找的答案。
    • 我编辑了这个问题。这不是一项微不足道的任务。我的文本每次都包含不同的单词。在大量文档中,我想找到特定短语的所有出现,例如“This Example”,然后是后面的括号(如果有的话)。 Spacy 也非常有用,因为我可以明确提到我想要在括号内添加形容词 (ADJ) 或名词 (NOUN)
    • 好的,我知道了,我已经编辑了我的答案。
    • 好的。我将再次添加我删除的点,但不幸的是,这不适用于 Spacy。标记被标记(名词、形容词等),因此并非所有标记都是相等的。我想匹配特定的标签。不是所有的人。谢谢你的回答。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-10
    相关资源
    最近更新 更多