目前正在为Coursera的Python工作,为每个人提供课程。这是前9.4。 由于某种原因,emcount是运行时应该是的两倍。这个问题似乎很早就开始了,因为它的数量应该是它的两倍。有谁知道我哪里出错了? 谢谢!
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
`
答案 0 :(得分:0)
我处理了您的代码,并进行了修改以使其正常工作。
不需要制作清单。只需将数据直接输入字典。
不需要else语句。您想继续检查新值是否大于旧值,如果是,则将其设为新值。
在if语句
之前,Bigcount和bigword都需要设置为None此外,如果第一遍的值为None,则需要if语句中的第二个条件。
将forword和bigcount的打印移到for循环外只打印一次结果。
还有一件事,作业说找到所有的行&#34; From&#34;,而不是&#34; From&#34;。看到区别?
我希望这会有所帮助。
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)
答案 1 :(得分:-1)
您需要做的唯一更改是更改for循环中的第一个if条件,并将其设置为“ From”并带有空格。