【问题标题】:Looping through a dictionary in python在python中循环遍历字典
【发布时间】:2023-03-12 08:40:01
【问题描述】:

我正在创建一个循环遍历字典的主函数,该字典对与之关联的所有值都有一个键。我遇到了麻烦,因为我无法让字典全部小写。我曾尝试使用 .lower 但无济于事。此外,程序应该查看句子的单词,确定它是否在用户之前称为“快乐”、“悲伤”或“中性”的句子中看到了更多这些单词(基于三个词典)并猜测将哪个标签应用于句子。

一个示例输出就像

Sentence: i started screaming incoherently about 15 mins ago, this is B's attempt to calm me down.
  0 appear in happy
  0 appear in neutral
  0 appear in sad
I think this is sad.
You think this is: sad
Okay! Updating.

代码:

import csv

def read_csv(filename, col_list):
"""This function expects the name of a CSV file and a list of strings
representing a subset of the headers of the columns in the file, and
returns a dictionary of the data in those columns, as described below."""

    with open(filename, 'r') as f:
        # Better covert reader to a list (items represent every row)
        reader = list(csv.DictReader(f))
        dict1 = {}
        for col in col_list:
            dict1[col] = []
            # Going in every row of the file
            for row in reader:
                # Append to the list the row item of this key
                dict1[col].append(row[col])
    return dict1

def main():
    dictx = read_csv('words.csv', ['happy'])
    dicty = read_csv('words.csv', ['sad'])
    dictz = read_csv('words.csv', ['neutral'])
    dictxcounter = 0
    dictycounter = 0
    dictzcounter = 0
    a=str(raw_input("Sentence: ")).split(' ')
    for word in a :
        for keys in dictx['happy']:
            if word == keys:
                 dictxcounter = dictxcounter + 1
        for values in dicty['sad']:
            if word == values:
                 dictycounter = dictycounter + 1
        for words in dictz['neutral']:
            if word == words:
                dictzcounter = dictzcounter + 1
    print dictxcounter
    print dictycounter
    print dictzcounter

【问题讨论】:

  • 如果col_list 是一个一个字符串的列表,这个表达式一定会因为解包错误而崩溃:dict1=dict((k, v.lower()) for k,v in col_list)。你确定你向我们展示了正确的代码吗?相同的语句还会覆盖您在循环中构建的字典,这可能解释了为什么您的代码无法按预期工作。
  • 你传递给read_csv一个字符串列表:['happy']。而这个列表就变成了形参col_list的值。
  • 我不知道你说的 >>> 是什么意思,但是你的程序现在的写法,col_list 是一个字符串的列表。
  • 例如:read_csv('words.csv', ['happy']) 产生 {'happy': ['ADORED', 'ADORING', 'ADORINGLY', 'ADVANCED'...
  • 好的,但我如何将整个内容创建为小写?

标签: python string csv dictionary count


【解决方案1】:

从您的代码中删除这一行:

dict1 = dict((k, v.lower()) for k,v in col_list)

它会覆盖您在循环中构建的字典。

【讨论】:

    最近更新 更多