python - 对单词和字符进行分组和分类

标签 python nltk hunspell

我需要在斜杠上拆分,然后报告标签。这是 hunspell 字典格式。我试图在 github 上找到一个可以执行此操作的类,但找不到。

# vi test.txt
test/S
boy
girl/SE
home/
house/SE123
man/E
country
wind/ES

代码:

from collections import defaultdict
myl=defaultdict(list)

with open('test.txt') as f :
    for l in f:
        l = l.rstrip()
        try:
            tags = l.split('/')[1]
            myl[tags].append(l.split('/')[0])
            for t in tags:
                myl[t].append( l.split('/')[0])
        except:
            pass

输出:

defaultdict(list,
            {'S': ['test', 'test', 'girl', 'house', 'wind'],
             'SE': ['girl'],
             'E': ['girl', 'house', 'man', 'man', 'wind'],
             '': ['home'],
             'SE123': ['house'],
             '1': ['house'],
             '2': ['house'],
             '3': ['house'],
             'ES': ['wind']})

SE组应该有3个词'girl', 'wind' and 'house'。应该没有 ES 组,因为它包含在内并且与“SE”相同,SE123 应该保持原样。我如何实现这一点?


更新:

我已经成功添加了双字母组,但如何添加 3、4、5 克?

from collections import defaultdict
import nltk
myl=defaultdict(list)

with open('hi_IN.dic') as f :
    for l in f:
        l = l.rstrip()
        try:
            tags = l.split('/')[1]
            ntags=''.join(sorted(tags))
            myl[ntags].append(l.split('/')[0])
            for t in tags:
                myl[t].append( l.split('/')[0])
            bigrm = list(nltk.bigrams([i for i in tags]))
            nlist=[x+y for x, y in bigrm]
            for t1 in nlist:
                t1a=''.join(sorted(t1))
                myl[t1a].append(l.split('/')[0])
        except:
            pass

我想如果我在源头对标签进行排序会有所帮助:

with open('test1.txt', 'w') as nf:
    with open('test.txt') as f :
        for l in f:
            l = l.rstrip()
            try:
                tags = l.split('/')[1]
            except IndexError:
                nline= l 
            else:
                ntags=''.join(sorted(tags))
                nline= l.split('/')[0] + '/' + ntags
            nf.write(nline+'\n')

这将创建一个带有排序标签的新文件 test1.txt。但是trigrams+的问题还是没有解决。


我下载了一个示例文件:

!wget https://raw.githubusercontent.com/wooorm/dictionaries/master/dictionaries/en-US/index.dic

使用“grep”命令的报告是正确的。

!grep 'P.*U' index1.dic

CPU/M
GPU
aware/PU
cleanly/PRTU
common/PRTUY
conscious/PUY
easy/PRTU
faithful/PUY
friendly/PRTU
godly/PRTU
grateful/PUY
happy/PRTU
healthy/PRTU
holy/PRTU
kind/PRTUY
lawful/PUY
likely/PRTU
lucky/PRTU
natural/PUY
obtrusive/PUY
pleasant/PTUY
prepared/PU
reasonable/PU
responsive/PUY
righteous/PU
scrupulous/PUY
seemly/PRTU
selfish/PUY
timely/PRTU
truthful/PUY
wary/PRTU
wholesome/PU
willing/PUY
worldly/PTU
worthy/PRTU

在排序的标签文件上使用二元组的 python 报告不包含上述所有单词。

myl['PU']

['aware',
 'aware',
 'conscious',
 'faithful',
 'grateful',
 'lawful',
 'natural',
 'obtrusive',
 'prepared',
 'prepared',
 'reasonable',
 'reasonable',
 'responsive',
 'righteous',
 'righteous',
 'scrupulous',
 'selfish',
 'truthful',
 'wholesome',
 'wholesome',
 'willing']

最佳答案

鉴于我的理解正确,这更多的是构建一个数据结构,对于给定的标签,构建正确的列表。我们可以通过构建一个只考虑单数标签的字典来做到这一点。稍后,当一个人查询多个标签时,我们计算交集。因此,这使得表示变得紧凑,并且易于提取,例如所有带有标签 AC 的元素,这将列出带有标签 ABCDACD< 的元素ZABC

因此我们可以构造一个解析器:

from collections import defaultdict

class Hunspell(object):

    def __init__(self, data):
        self.data = data

    def __getitem__(self, tags):
        if not tags:
            return self.data.get(None, [])

        elements = [self.data.get(tag ,()) for tag in tags]
        data = set.intersection(*map(set, elements))
        return [e for e in self.data.get(tags[0], ()) if e in data]

    @staticmethod
    def load(f):
       data = defaultdict(list)
       for line in f:
           try:
               element, tags = line.rstrip().split('/', 1)
               for tag in tags:
                   data[tag].append(element)
               data[None].append(element)
           except ValueError:
               pass  # element with no tags
       return Hunspell(dict(data))

__getitem__ 末尾的列表处理是为了以正确的顺序检索元素。

然后我们可以将文件加载到内存中:

>>> with open('test.txt') as f:
...     h = Hunspell.load(f)

并查询任意键:

>>> h['SE']
['girl', 'house', 'wind']
>>> h['ES']
['girl', 'house', 'wind']
>>> h['1']
['house']
>>> h['']
['test', 'girl', 'home', 'house', 'man', 'wind']
>>> h['S3']
['house']
>>> h['S2']
['house']
>>> h['SE2']
['house']
>>> h[None]
['test', 'girl', 'home', 'house', 'man', 'wind']
>>> h['4']
[]

查询不存在的标签将导致一个空列表。因此,我们在这里推迟调用时的“交叉”过程。我们实际上已经可以生成所有可能的交集,但这将导致数据结构庞大,并且可能需要大量工作

关于python - 对单词和字符进行分组和分类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53097193/

相关文章:

python - 获取字典中最长的元素

python - 从命令行或 pkg 中的可执行文件运行时,Py2app 构建可以完美运行,但双击应用程序时则无法运行

python Selenium : Finds h1 element but returns empty text string

Python 地理无法找到美国的城市

linux - 使用命令行以非交互方式对文件进行拼写检查

python - 当 DEBUG = False 时如何在 Django 2.* 中提供静态文件?

python - nltk.tokenize 从 Shell 正确执行,但作为脚本文件出现错误

scikit-learn - 混淆矩阵 - 测试情感分析模型

Hunspell - 无法打开名为 en_US 的字典的词缀或字典文件

silverlight - 将 Hunspell 与 Silverlight 结合使用