首页 > 解决方案 > Python:自然语言处理 (NLP)

问题描述

我在 HiveQL 数据库中有十亿个字符串。我正在将它们加载到 Python 中。字符串不是用空格分隔的,看起来像:

"mynameisanon"
...
"helloworld"

我想计算每个字符串中的单词数。但首先,我需要一本字典。我不知道如何获取单词词典,但假设我有以下词典:

{ hello, world, my, name, is}

然后该功能将像这样工作:

Input:  mynameisanon
Output: 3

Input:  helloworld
Output: 2

最后,我想要一张 Pandas 桌子。

标签: pythonpandas

解决方案


正如我在评论中提到的,在一般情况下,这不能唯一完成,但假设有一个字典可以解释这一点:

(没有特别好测试):

strings = ["mynameisanon", "helloworld"]

words = ["hello", "world", "my", "name", "is"]

for string in strings:
    count = 0
    max_interval = len(string)
    for interval_length in range(1,max_interval+1):
        for interval_start in range(0, len(string)+1-interval_length):
            interval = string[interval_start:(interval_start+interval_length)]
            if interval in words:
                count += 1
    print(string)
    print(count)

这假设单词可以小到一个字母,也可以和整个字符串一样长,并检查这些值之间所有长度的单词


推荐阅读