Разделение предложений со словом «но» с помощью RegEx

Я пытаюсь разбить предложения на куски, используя RegEx в слове «но» (или любых других координирующих словах союза). Это не работает...

sentence = nltk.pos_tag(word_tokenize("There are no large collections present but there is spinal canal stenosis."))
result = nltk.RegexpParser(grammar).parse(sentence)
DigDug = nltk.RegexpParser(r'CHUNK: {.*<CC>.*}')
for subtree in DigDug.parse(sentence).subtrees(): 
    if subtree.label() == 'CHUNK': print(subtree.node())

Мне нужно разделить предложение "There are no large collections present but there is spinal canal stenosis." на два:

1. "There are no large collections present"
2. "there is spinal canal stenosis."

Я также хочу использовать тот же код для разделения предложений на «и» и других словах сочинительного союза (CC). Но мой код не работает. Пожалуйста помоги.


person Code Monkey    schedule 25.08.2018    source источник


Ответы (2)


Я думаю, вы можете просто сделать

import re
result = re.split(r"\s+(?:but|and)\s+", sentence)

куда

`\s`        Match a single character that is a "whitespace character" (spaces, tabs, line breaks, etc.)
`+`         Between one and unlimited times, as many times as possible, giving back as needed (greedy)
`(?:`       Match the regular expression below, do not capture
            Match either the regular expression below (attempting the next alternative only if this one fails)
  `but`     Match the characters "but" literally
  `|`       Or match regular expression number 2 below (the entire group fails if this one fails to match)
  `and`     Match the characters "and" literally
)
`\s`        Match a single character that is a "whitespace character" (spaces, tabs, line breaks, etc.)
`+`         Between one and unlimited times, as many times as possible, giving back as needed (greedy)

Вы можете добавить туда больше слов-сочетаний, разделив их вертикальной чертой |. Однако следите за тем, чтобы эти слова не содержали символов, имеющих особое значение в регулярном выражении. Если вы сомневаетесь, сначала избегайте их с помощью re.escape(word)

person Theo    schedule 25.08.2018

Если вы хотите избежать жесткого кодирования слов-сочетаний, таких как «но» и «и», попробуйте чинить вместе с фрагментированием:


import nltk
Digdug = nltk.RegexpParser(r""" 
CHUNK_AND_CHINK:
{<.*>+}          # Chunk everything
}<CC>+{      # Chink sequences of CC
""")
sentence = nltk.pos_tag(nltk.word_tokenize("There are no large collections present but there is spinal canal stenosis."))

result = Digdug.parse(sentence)

for subtree in result.subtrees(filter=lambda t: t.label() == 
'CHUNK_AND_CHINK'):
            print (subtree)

Щелчок в основном исключает то, что нам не нужно, из фрагмента фразы — «но» в данном случае. Для получения дополнительной информации см.: http://www.nltk.org/book/ch07.html< /а>

person Maria Thomas    schedule 27.11.2018