python - 给定所有两个连续单词出现的文本计数

标签 python python-3.x dictionary n-gram


输入:

Once upon a time a time this upon a


输出:

dictionary {
    'Once upon': 1,
       'upon a': 2,
       'a time': 2,
       'time a': 1,
    'time this': 1,
    'this upon': 1
}


代码:

def countTuples(path):
    dic = dict()
    with codecs.open(path, 'r', 'utf-8') as f:
        for line in f:
            s = line.split()
            for i in range (0, len(s)-1):
                dic[str(s[i]) + ' ' + str(s[i+1])] += 1
    return dic

我收到这个错误:

File "C:/Users/user/Anaconda3/hw2.py", line 100, in countTuples
    dic[str(s[i]) + ' ' + str(s[i+1])] += 1
TypeError: list indices must be integers or slices, not str

如果我删除 += 并只放置 =1 一切正常,我想问题是当我尝试访问一个条目以提取一个值时还不存在吗?

我该怎么做才能解决这个问题?

最佳答案

您可以使用 defaultdict使您的解决方案工作。使用 defaultdict,您可以指定键值对值的默认类型。这允许您对尚未显式创建的 key 进行类似 +=1 的赋值:

import codecs
from collections import defaultdict

def countTuples(path):
    dic = defaultdict(int)
    with codecs.open(path, 'r', 'utf-8') as f:
        for line in f:
            s = line.split()
            for i in range (0, len(s)-1):
                dic[str(s[i]) + ' ' + str(s[i+1])] += 1
    return dic

>>> {'Once upon': 1,
     'a time': 2,
     'this upon': 1,
     'time a': 1,
     'time this': 1,
     'upon a': 2})

关于python - 给定所有两个连续单词出现的文本计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43411602/

相关文章:

python - key :Value Pairs from txt file into a dictionary

python - 如何缩短多个 IF .... IN ... OR 语句?

python - numpy 'module' 对象没有属性 'stack'

Python 无法找到 Elasticsearch

python - Pygame - 在 pygame 窗口周围移动一个正方形,但在改变方向时无法停止当前移动,导致正方形沿对角线移动

java - 在 onMapReady 回调中使用 if 会产生问题吗?

python - 如何让 python unittest 测试函数是否返回 csv.reader 对象?

python-3.x - 从 Google 新闻向量数据集中减少 word2vec 维度

css - Scrapy 在 Xpath 或 Css 中找不到文本

c# - 不区分大小写的字典未按预期工作