Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/362.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python字典中迭代和打印单词_Python_Dictionary_Output - Fatal编程技术网

在python字典中迭代和打印单词

在python字典中迭代和打印单词,python,dictionary,output,Python,Dictionary,Output,我正在学习python,我喜欢用这么少的代码就能完成多少工作,但我对语法感到困惑。我只是试着遍历一个字典并打印出每个条目和值 这是我的密码: words = {} value = 1 for line in open("test.txt", 'r'): for word in line.split(): print (word) try: words[word] += 1 except KeyError:

我正在学习python,我喜欢用这么少的代码就能完成多少工作,但我对语法感到困惑。我只是试着遍历一个字典并打印出每个条目和值

这是我的密码:

words = {}
value = 1

for line in open("test.txt", 'r'):
    for word in line.split():
        print (word)
        try:
            words[word] += 1
        except KeyError:
            #wur you at key?
            print("no")
            words[word]=1

for item in words:
    print ("{",item, ": ", words[item][0], " }")

我当前的print语句不起作用,我找不到使用多个变量的大型print语句的好例子。如何正确地打印它?

在这里迭代字典的最佳方法是按键和值循环,每次循环时解压键值元组:

for item, count in words.items():
    print("{", item, ": ", count, "}")
另外,在构建阵列的循环中,并不需要异常处理逻辑。如果键不在字典中,则字典的get方法可以返回默认值,从而将代码简化为:

words[word] = words.get(word, 0) + 1

您的问题似乎是您正在尝试打印单词[item][0],但单词[item]始终是一个数字,无法为数字编制索引

所以,只是…不要这样做:

print ("{",item, ": ", words[item], " }")
这就足够修复它了,但有一些方法可以改进此代码:

print with multiple arguments在每个参数之间放置一个空格,因此您将最终打印{item:3},而您可能不需要所有这些空格。您可以通过使用关键字参数sep=来解决这个问题,但更好的解决方案是使用字符串格式或%运算符。 通过迭代words.items而不是words,可以同时获取键和值。 通过使用setdefault方法,或者通过使用defaultdict,或者更简单地说,您可以使用计数器,将整个存储简化为一个默认值。 最好使用with语句关闭打开的文件。 保持风格一致,不要在某些函数后加空格,但不要在其他函数后加空格。 因此:

您可以使用dict.get并消除try和except块

words = {}

for line in open("test.txt", 'r'):
    for word in line.split():
        print (word)
        words[word] = words.get(word,0) +1

for word,count in words.items():
    print(word,count)
dict.get返回键(如果字典中存在),否则返回默认值 语法:dict.getkey[,默认值]

您还可以覆盖\uuuu缺失\uuuuu:


你说不工作是什么意思?如果您向我们提供了一个示例,或者包含test.txt的内容,或者更好,包含源代码中刚刚定义的单词,这会有所帮助。然后您可以显示预期的和实际的输出。我得到以下错误:ValueError:太多的值无法解压缩预期的2这是错误的。当你迭代一个dict时,你只得到它的键,而不是它的键值对。如果您想要后者,您必须使用我在回答中解释的items方法。而且,这并不能真正解释他的代码出了什么问题;如果您将他的代码翻译为使用items,那么将是针对item、words in words.items:和print调用中的word[0],您将得到与他开始时完全相同的错误。修复了使用items的问题。我不认为我特别需要解释为什么OP的代码是错误的,因为你这样做了。在我看来,我在这个答案中给出的代码是实现这一点的最佳方式;这是因为它读起来更地道。当我最初发布答案时,我忘记了这些东西是需要的。谢谢!我正在尝试解决一些基本的python问题,以掌握它,我还有很多东西要学习。
words = {}

for line in open("test.txt", 'r'):
    for word in line.split():
        print (word)
        words[word] = words.get(word,0) +1

for word,count in words.items():
    print(word,count)
class my_dict(dict):
    def __missing__(self,key):
        return 0


words = my_dict()

for line in open("test.txt", 'r'):
    for word in line.split():
        print (word)
        words[word] += 1

for word,count in words.items():
    print(word,count)