繁体   English   中英

如何更新 Python 中字典中的列表值

[英]How to update list value in dictionary in Python

初学者在这里。 我目前正在编写一个程序,它将“电影评论”文本文件中的每个单词变成一个键,存储一个包含评论编号和单词被看到次数的列表值。 例如:

4 I loved it

1 I hated it

... 可能看起来像字典:

words['i']     = [5,2]

words['loved'] = [4,1]

words['it']    = [5,2]

words['hated'] = [1,1]

但是,这是我得到的 output:

{'i': [1, 2], 'loved': [4, 1], 'it': [1, 2], 'hated': [1, 1]}

我想出了柜台部分,但我不知道如何更新评论号。 到目前为止,这是我的代码:

def main():

    reviews = open("testing.txt", "r")
    data = reviews.read();
    reviews.close()

    # create new dictionary
    words = {}

    # iterate over every review in text file
    splitlines = data.split("\n")

    for line in splitlines:
        lower = line.lower()
        value = lower.split()
        rev = int(value[0])
        for word in value:
            if word.isalpha():
                count = 1
                if word not in words:
                    words[word] = [rev, count]
                else:
                    words[word] = [rev, count + 1]

如何更新评论数?

这很容易做到。 假设每个键在值列表中只有 2 项:

if word not in words:
    words[word] = [rev, 1]
else:
    temp = words[word][1]
    words[word] = [rev, temp + 1]

更新计数时,您使用的是count + 1 ,但此处的count将始终为 1; 您需要先检索现有计数,使用类似: count = words[word][1]

暂无
暂无

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

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