考虑两个连续单词作为一个词频

2024-09-24 00:22:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这样一句话:

Sentence
    Who the president of Kuala Lumpur is?

我正在尝试提取所有单词(标记化)

low_case = df['Sentence'].str.lower().str.cat(sep=' ')
words = nltk.tokenize.word_tokenize(low_case)
word_dist = nltk.FreqDist(words)

example = pd.DataFrame(word_dist.most_common(1000),
                    columns=['Word', 'Freq'])

但是,我想将吉隆坡提取为双格,因此我正在考虑一个过滤器,它会显示“如果有两个连续的单词有大写字母,则将它们提取为唯一的单词。 因此,如果我有以下清单:

    Who the president of Kuala Lumpur is?

我会(使用上面的代码):

Word            Freq
who               1
is                1
president         1
of                1
Kuala             1
Lumpur            1 
is                1

但我想要这个:

Word            Freq
who               1
is                1
president         1
of                1
Kuala Lumpur      1
is                1

我认为要找到两个连续的大写字母,我应该应用以下模式:

pattern = r"[A-Z]{2}-\d{3}-[A-Z]{2}"

o安奇:

re.findall('([A-Z][\w-]*(?:\s+[A-Z][\w-]*)+)', df.Sentence.tolist())

但是我不知道如何在上面的代码中包含这些信息


Tags: ofthedfis单词sentencewordlow
1条回答
网友
1楼 · 发布于 2024-09-24 00:22:22

您可以进行一些预处理,并使用re Match Objects将双格从句子的其余部分分离出来。例如:

import re

# initialize sentence text
sentence_without_bigrams = 'Who the president of Kuala Lumpur or Other Place is?'
bigrams = []

# loop until there are no remaining bi-grams
while True:
    # find bi-grams
    match = re.search('([A-Z][\w-]*(?:\s+[A-Z][\w-]*)+)', sentence_without_bigrams)
    if match == None:
        break
    else:
        # add bi-gram to list of bi-grams
        bigrams.append(sentence_without_bigrams[match.start():match.end()])
        # remove bigram from sentence
        sentence_without_bigrams = (sentence_without_bigrams[:match.start()-1] + sentence_without_bigrams[match.end():])


print(bigrams)
>> ['Kuala Lumpur', 'Other Place']

print(sentence_without_bigrams)
>> Who the president of or is?

但是,这个解决方案没有达到您的最终目标,因为像'Hello, Mr President Obama'这样的句子不会被正确捕获(如here

相关问题 更多 >