【发布时间】:2020-02-02 19:00:56
【问题描述】:
我正在学习 Python,但遇到了一些我自己无法弄清楚的事情。
我有一个文本文件 mbox-short.txt,其中包含如下行:
From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008
Return-Path: <postmaster@collab.sakaiproject.org>
Received: from murder (mail.umich.edu [141.211.14.90])
From louis@media.berkeley.edu Fri Jan 4 18:10:48 2008
Return-Path: <postmaster@collab.sakaiproject.org>
Received: from murder (mail.umich.edu [141.211.14.97])
From zqian@umich.edu Fri Jan 4 16:10:39 2008
Return-Path: <postmaster@collab.sakaiproject.org>
Received: from murder (mail.umich.edu [141.211.14.25])
以下代码可以正常工作:
x = open('mbox-short.txt')
y = dict()
count = int()
for line in x: # read every line of <file>
if line.startswith('From '): # check if <line> starts with <'From '>
line1 = line.split(' ') # split <line> into separate words -> <line1>
count = count + 1 # count every <'From '> occurence
w = line1[1] # 2nd word of <line1>
if w not in y: # check if 2nd word of <line1>(=w) is already in dict <y>
y[w] = 1 # add 2nd word of <line1> as key with <value>=1
else:
y[w] += 1 # or +1 to <value>
print(y)
即使在开始时 y 仍然是一个空字典,它也可以工作。
输出:
{'stephen.marquard@uct.ac.za': 2, 'louis@media.berkeley.edu': 3, ... 'ray@media.berkeley.edu': 1}
在我正在使用的教程中,还有另一个示例,使用 .get 方法:
word = 'brontosaurus'
d = dict()
for c in word:
d[c] = d.get(c,0) + 1
print(d)
当我尝试这样做时:
x = 'file'
y = dict()
count = int()
for line in x: # read every line of <file>
if line.startswith('From '): # check if <line> starts with <'From '>
line1 = line.split(' ') # split <line> into separate words -> <line1>
count = count + 1 # count every <'From '> occurence
w = line1[1] # 2nd word of <line1>
for w in y: # alternate + simplified form using <dict.get> method
y[w] = y.get(w,0) + 1 # check if <w> is already in dict y, if not, add it
print(y)
失败了。输出:
{}
使用调试器我可以看到for w in y: 循环没有被执行。它只是跳出y。
我不明白为什么。
【问题讨论】:
-
如果
y为空,您希望for w in y:做什么?没有什么可以迭代的。 -
我没有看到您打开要阅读的文件的位置。您使用
open打开文件 -
是的,这不是minimal reproducible example - 请编辑您的代码,以便有人可以将其粘贴到文件中并运行它无需添加任何其他内容
-
这不是您从文件中读取的方式。请参阅realpython.com/read-write-files-python/… 上的“遍历文件中的每一行”
-
@barny - 无法弄清楚如何为我的代码制作一个最小的可重现示例,只是为了愚蠢:-(
标签: python dictionary for-loop