【问题标题】:Count the occurrences of bigrams in string and save them into a dictionary计算字符串中二元组的出现次数并将它们保存到字典中
【发布时间】:2020-03-09 14:48:54
【问题描述】:

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

您能帮我开始吗?
最好的问候!

【问题讨论】:

  • 请分享您所做的代码minimal reproducible example并解释它有什么问题。
  • 次要问题:Python 中的元组是零个或多个项目的不可变序列。这并不意味着一对。
  • @Jonas 我认为你的意思是 bigram (这是一个 n-gram for n = 2),至少来自你的示例输出。
  • @StevenRumbalski@hitter 啊我明白了。我只从数学中知道这个术语:D。谢谢你的澄清。

标签: python string dictionary


【解决方案1】:

给定

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})

【讨论】:

  • 感谢您的回复。这工作得很好!
【解决方案2】:

附带说明,您正在寻找bigrams。对于更大的规模——在不同的机器学习/NLP 工具包中都有强大的实现。

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

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

问题 #1 的解决方案是来自 itertools recipespairwise

问题 #2 的解决方案是Counter


综合起来就是

from itertools import tee

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

Counter(pairwise('test string'))

【讨论】:

    【解决方案3】:

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

    首先,我们使用join()从字符串中删除所有空格。
    然后我们构造一个包含所有子字符串的list,步长为2
    最后我们构造 print()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}
    

    【讨论】:

    • 嗨@hitter,这确实对我有用,但是我关心的字符串非常大,所以如果我想打印“substr”,它会使我的 jupiter notebook 崩溃:D 它与柜台。有没有办法让这更有效?或者你知道有什么区别吗?我对这个话题很陌生,所以请原谅我的经验不足。
    • 嘿@Jonas,我对代码做了一点改动,现在首先构建字典,然后获取printed。我在想也许这会使其效率更高一些。如果是,请告诉我,再次感谢您的支持。
    猜你喜欢
    • 2018-01-01
    • 2020-05-06
    • 2014-09-13
    • 1970-01-01
    • 1970-01-01
    • 2014-06-03
    • 1970-01-01
    • 1970-01-01
    • 2014-04-24
    相关资源
    最近更新 更多