gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 02:08:25 25 4
gpt4 key购买 nike


输入:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com