【问题标题】:Use of Dictionary in PythonPython中字典的使用
【发布时间】:2016-08-08 10:10:13
【问题描述】:

我正在做 Coursera python 练习,但在编写代码时遇到了问题。

问题如下:

编写一个程序来读取 mbox-short.txt 并找出谁发送的邮件数量最多。程序查找“From”行并将这些行的第二个单词作为发送邮件的人。

程序创建一个 Python 字典,将发件人的邮件地址映射到它们在文件中出现的次数。生成字典后,程序使用最大循环读取字典以找到最多产的提交者。 示例文本文件在这一行:http://www.pythonlearn.com/code/mbox-short.txt

预期的输出应该是:

cwen@iupui.edu 5

这是我的代码:

 name = raw_input("Enter file:")
if len(name) < 1 : name = "mbox-short.txt"
name="mbox-short.txt"
handle=open(name)
text=handle.read()
for line in handle:
    line=line.rstrip()
    words=line.split()
    if words==[]: continue
    if words[0]!='From':continue
    words2=words[1]
words3=words2.split()
counts=dict()
for word in words3:
     counts[word]=counts.get(word,0)+1



bigcount=None
bigword=None
for key,val in counts.items():
 if val>bigcount:
    bigword=key
    bigcount=val
print bigword,bigcount

我的输出是: cwen@iupui.edu 1

我的代码中的错误在哪里?

【问题讨论】:

  • 不知道。怎么了?
  • 尝试使用for line in text 而不是for line in handle
  • 我的输出应该是 cwen@iupui.edu 5。但它即将到来 cwen@iupui.edu 1
  • @dhdavvie 我试过了,但它不起作用
  • 除了words2 上的NameError,我看不到它是如何产生任何东西的,因为handle 应该是空的,因为已经完成了handle.read(),然后只定义了words2 for line in handle 循环,因为文件对象的指针在末尾,所以该循环中的任何内容都不会执行。

标签: python python-2.7 python-3.x dictionary


【解决方案1】:

这是您需要的代码,您没有将 words2 输出存储在列表中,并且如 cmets 中所述,您也在以错误的方式递归文件。

希望这会对你有所帮助。

name = raw_input("Enter file:")
if len(name) < 1 : name = "mbox-short.txt"
name="mbox-short.txt"
handle=open(name)
words3 = []
for line in handle:
    line=line.rstrip()
    words=line.split()
    if words==[]: continue
    if words[0]!='From':continue
    words2=words[1]
    words3.append(words2.split()[0])
    # print words
counts=dict()
for word in words3:
     counts[word]=counts.get(word,0)+1


bigcount=None
bigword=None
for key,val in counts.items():
 if val>bigcount:
    bigword=key
    bigcount=val
print bigword,bigcount

【讨论】:

  • 无需读取文件、拆分文件并遍历结果列表。您可以跳过它并遍历文件对象本身。
  • @TigerhawkT3 谢谢老兄,我不知道。
  • 你能解释一下'words3.append(words2.split()[0])'的用法吗?其实我是 python 新手...
  • 拆分它并获取拆分后得到的该数组的第一个元素。
  • 在您认为没有得到任何东西的地方使用打印语句,它会为您打印出来,便于理解。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-01-22
  • 2017-10-26
  • 1970-01-01
  • 2014-05-03
  • 2018-09-28
  • 1970-01-01
  • 2021-12-21
相关资源
最近更新 更多