繁体   English   中英

计算字符串中二元组的出现次数并将它们保存到字典中

[英]Count the occurrences of bigrams in string and save them into a dictionary

我用 Python 编码,我有一个字符串,我想计算该字符串中二元组的出现次数。 我的意思是,例如,我有一个字符串"test string" ,我想在大小为 2 的子字符串中遍历该字符串,并创建一个包含每个二元组及其在原始字符串中出现次数的字典细绳。
因此,我想获得{te: 1, es : 1, st: 2, ...}形式的输出。

你能帮我开始吗?
此致!

给定的

s = "test string"

from collections import Counter
Counter(map(''.join, zip(s, s[1:])))

或者

from collections import Counter
Counter(s[i:i+2] for i in range(len(s)-1))

两者的结果是

Counter({'st': 2, 'te': 1, 'es': 1, 't ': 1, ' s': 1, 'tr': 1, 'ri': 1, 'in': 1, 'ng': 1})

作为旁注,您正在寻找bigrams 对于更大的规模——在不同的机器学习/NLP 套件中有强大的实现。

作为临时解决方案,问题应该分解为

  1. 按顺序迭代“当前和下一个元素”
  2. 计算独特的对。

解决方案问题#1是pairwiseitertools食谱

问题#2 的解决方案是Counter


放在一起是

from itertools import tee

def pairwise(iterable):
    a, b = tee(iterable)
    next(b, None)
    return zip(a, b)

Counter(pairwise('test string'))

我认为这样的事情简单易行,不需要import任何库。

首先,我们使用join()从字符串中删除所有空格。
然后我们构造一个包含所有子字符串的list ,步长为2
最后,我们构造并print() dictionary ,该dictionary将所有子字符串作为键,并将它们各自在原始字符串中的出现作为值。

substr = [] # Initialize empty list that contains all substrings.
step = 2 # Initialize your step size.
s = ''.join('test string'.split()) # Remove all whitespace from string.
for i in range(len(s)):
    substr.append(s[i: i + step])
# Construct and print a dictionary which counts all occurences of substrings.
occurences = {k: substr.count(k) for k in substr if len(k) == step}
print(occurences) 

运行时,它会根据您的要求输出一个字典:

{'te': 1, 'es': 1, 'st': 2, 'ts': 1, 'tr': 1, 'ri': 1, 'in': 1, 'ng': 1}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM