python - NLTK 正则表达式分块器不在一个命令中处理多个语法规则

标签 python regex python-3.x nltk text-chunking

我正在尝试从我的语料库中提取短语,为此我定义了两个规则,一个是名词后跟多个名词,另一个是形容词后跟名词,在这里我希望如果从两个规则中提取相同的短语,程序应该忽略第二个,我面临的问题是这些短语仅从第一条规则中提取,而第二条规则没有被应用。 下面是代码:

PATTERN = r"""
      NP: {<NN><NN>+}
      {<ADJ><NN>*}

       """
    MIN_FREQ = 1
    MIN_CVAL = -13 # lowest cval -13
    def __init__(self):
        corpus_root = os.path.abspath('../multiwords/test')
        self.corpus = nltk.corpus.reader.TaggedCorpusReader(corpus_root,'.*')
        self.word_count_by_document = None
        self.phrase_frequencies = None

def calculate_phrase_frequencies(self):
        """
       extract the sentence chunks according to PATTERN and calculate
       the frequency of chunks with pos tags
       """

        # pdb.set_trace()
        chunk_freq_dict = defaultdict(int)
        chunker = nltk.RegexpParser(self.PATTERN)

        for sent in self.corpus.tagged_sents():

            sent = [s for s in sent if s[1] is not None]

            for chk in chunker.parse(sent).subtrees():

                if str(chk).startswith('(NP'):                  

                    phrase = chk.__unicode__()[4:-1]

                    if '\n' in phrase:
                        phrase = ' '.join(phrase.split())

                    just_phrase = ' '.join([w.rsplit('/', 1)[0] for w in phrase.split(' ')])
                   # print(just_phrase)
                    chunk_freq_dict[just_phrase] += 1
        self.phrase_frequencies = chunk_freq_dict
        #print(self.phrase_frequencies)

最佳答案

首先,Python,尤其是多行字符串是缩进相关的。确保字符串中没有前面的空格(因为它们将被视为字符)并确保模式(括号)在视觉上对齐。

此外,我认为您可能想要 <ADJ><NN>+作为你的第二个模式。 +表示 1 个或多个,而 *表示 0 个或多个。

希望这能解决问题。

#!/usr/bin/env python
import nltk

PATTERN = r"""
NP: {<NN><NN>+}
    {<ADJ><NN>+}
"""

sentence = [('the', 'DT'), ('little', 'ADJ'), ('yellow', 'ADJ'),
            ('shepherd', 'NN'), ('dog', 'NN'), ('barked', 'VBD'), ('at', 'IN'),
            ('the', 'DT'), ('silly', 'ADJ'), ('cat', 'NN')]

cp = nltk.RegexpParser(PATTERN)
print(cp.parse(sentence))

结果:

(S
  the/DT
  little/ADJ
  yellow/ADJ
  (NP shepherd/NN dog/NN)
  barked/VBD
  at/IN
  the/DT
  (NP silly/ADJ cat/NN))

引用:http://www.nltk.org/book/ch07.html

关于python - NLTK 正则表达式分块器不在一个命令中处理多个语法规则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48186483/

相关文章:

python - ManyToManyField 在使用自定义主键时引用 'id' 字段

python - 如何将字符串拆分为命令行参数,如 python 中的 shell?

c++ - wregex 有什么问题?wregex 不支持 native c++ 中的 [group] 功能?

c# - 将 c# 正则表达式转换为 javascript 正则表达式

python - 在python中定位大数据集中的多个文件

python-3.x - 具有多个客户端和无限循环的 Python 异步协议(protocol)行为

python - 如何找到用 matplotlib 绘制的图传递的像素

python - 在python中解密ssl加密数据

regex - (?^ :…) mean in the string form of a Perl qr//Regex? 中的插入符号 ^ 是什么

Python 语法错误 : Non-UTF-8