-1

目前正在为 Coursera 的 Python For everyone 课程做此工作。这是前 9.4。由于某种原因,emcount 是运行时应有的两倍。这个问题似乎很早就开始了,因为 line 的数量是它应该的两倍。有谁知道我哪里出错了?谢谢!

name = input("Enter file:")
if len(name) < 1 : name = "mbox-short.txt"

handle = open(name)

lst = list()
#emcount = dict()
for line in handle:
    if not line.startswith("From"): continue
    line=line.split()
    print(line)
    lst.append(line[1])#adding each email occurrence to lst
#    print(lst)
emcount = dict()
for word in lst:
    emcount[word] = emcount.get(word,0)+1
#    print(emcount)

bigcount = 0#empty at beginning
bigword = None
for word,count in emcount.items():
    #items give you acopy of each key value pair, word is the key
    if bigcount> count:
        bigcount = bigcount
        bigword = bigword
        print(bigword, bigcount)
    else:
        bigcount = count
        bigword = word


`
4

2 回答 2

2

我处理了您的代码,并进行了修改以使其正常工作。

不需要列出清单。只需将数据直接放入字典即可。

不需要 else 语句。您想继续检查新值是否大于旧值,如果是,则将其设为新值。

Bigcount 和 bigword 都需要在 if 语句之前设置为 None

此外,如果第一遍的值为 None ,则在 if 语句中需要第二个条件。

并将 bigword 和 bigcount 的打印移到 for 循环之外,只打印一次结果。

还有一件事,作业说要找到所有带有“From”的行,而不是带有“From”的行。看到不同?

我希望这有帮助。

name = input("Enter file:")
if len(name) < 1 : name = "mbox-short.txt"
handle = open(name)
emcount = dict()
for line in handle:
    if not line.startswith("From "): continue
    line = line.split()
    line = line[1]
    emcount[line] = emcount.get(line, 0) +1 
bigcount = None
bigword = None
for word,count in emcount.items():
if bigcount == None or count > bigcount:
    bigcount = count
    bigword = word
print(bigword, bigcount)
于 2018-06-14T16:02:13.797 回答
-1

您需要做的唯一更改是更改 for 循环中的第一个 if 条件,并将其设置为带有空格的“From”。

于 2020-11-19T14:08:02.450 回答