从文件创建字典并添加值

问题描述 投票:0回答:1

*更新为我先前的帖子已被删除,并且出现错误。

我必须打开一个文本文件,并将其导入字典。文本文件包含2条信息:产品ID和客户评论字符串。我的目标是通读提供的客户反馈,并计算每个产品ID的评论中出现好或坏关键字的次数。请注意,某些产品评论两次包含相同的好/坏词。

我的最终目标是能够显示每个产品出现的好词和坏词的数量。然后,我将把好关键字和坏关键字加在一起,以显示全部关键字。我得到用户帮助的以下内容,但被卡在柜台上。另外,我最初创建了一个class,但被告知这是不必要的。

[我的代码在尝试通过字典中的for循环来计算好和坏单词的每个实例时给了我KeyError。另外,我的计数器似乎没有正确设置

我的问题是,如何正确创建一个计数器,以总计每个产品ID的好词和坏词的数量?计数器必须考虑重复的单词。

dictionary = {}
good = ("perfect", "nice")
bad = ("broken", "wrong", "terrible")     
with open("products.txt","r") as products:
    for line in products:
        p = line.split(',',1)[0]
        f = line.split(',',1)[1]
        dictionary[p] = v.lower()
print(products)

for c in dictionary:
    for word in dictionary[c].f().split():
        if word in good:
            dictionary[c]+=1
        if word in bad:
            dictionary[c]+=1

for k in dictionary.keys():
    print(dictionary[k].productID,dictionary[k].good,dictionary[k].bad)

文本文件的前几行内容如下:

4321,项目在收到时被损坏。糟糕的产品。5432,好产品6321,我收到了错误的物品。现在,我被告知无法退回错误的物品。多么可怕!

python string dictionary counter
1个回答
0
投票

我不太确定我是否了解您的需求,但这是您要找的吗?

import re
dictionary = {}
good = ("perfect", "nice" )
bad = ("broken", "wrong", "terrible")     
with open("products.txt","r") as products:
    for line in products:
        p = line.split(',',1)[0]
        f = line.split(',',1)[1]
        f = re.sub('\?|\.|\!|\/|\;|\:|\´|\`|\*|\¨|\%|\(|\)|\&|\$|\=|\+|\,|\[|\]\'\"', '', f) #remove pontuation
        dictionary[p] = {'text':f.lower(),'good':0,'bad':0}

for c in dictionary:
    for word in dictionary[c]['text'].split():
        if word in good:
            dictionary[c]['good'] += 1
        if word in bad:
            dictionary[c]['bad'] += 1

for k in dictionary.keys():
    print("id = %s, text = %s, good = %i, bad = %i" % (k,dictionary[k]['text'],dictionary[k]['good'],dictionary[k]['bad']))
© www.soinside.com 2019 - 2024. All rights reserved.