python - 对单词和字符进行分组和分类
问题描述
我需要拆分斜线,然后报告标签。这是 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组应该有“女孩”、“风”和“房子”三个词。应该没有 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
,这将列出带有标签ABCD
、、ACD
等的元素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']
[]
查询不存在的标签将导致一个空列表。因此,我们在这里推迟调用时的“交叉”过程。事实上,我们已经可以生成所有可能的交集,但这会导致数据结构庞大,并且可能需要大量工作
推荐阅读
- reactjs - 打字稿将自定义对象分配给任何对象
- mongodb - 操作 `mytables.insertOne()` 缓冲在 10000 毫秒后超时
- python - 当我将列表嵌套在字典中时,我对如何更改列表中的字符串感到困惑
- r - 如何在R中的计算器中解析字符串?
- python - 查询文件保存操作
- openssl - Ubuntu - OpenSSL:错误:1408F10B:SSL 例程:ssl3_get_record:错误的版本号
- snaplogic - Snaplogic:如何以非等于(如、>、<)的条件连接两个表
- huggingface-transformers - HuggingFace 中的自定义日志记录
- typescript - vue3 setup() 参数的正确 typeScript 类型
- java - 在 Eclipse 中运行 spring boot maven 项目时面临问题,该项目在运行时被终止