我正在使用python计算.txt文件中一行中紧跟在名字后面的名字的数量,以确定谁的名字后面最多,代码如下:
lines=0
wordCount=0
mostWordsInLine = 0
follows = open("follows.txt", "r")
for word in follows:
lines += 1
f1=word.split()
wordCount=wordCount+len(f1)
if len(f1) > mostWordsInLine:
mostWordsInLine = len(f1)
mostWordsInLine = word[: word.find(' ')]
print ("Most social user: " + str(mostWordsInLine))
.txt文件如下所示:
andrew fred
fred
judy andrew fred
george judy andrew
john george
我得到的结果是:
Most social user: andrew
我的问题是我的代码应该返回judy和george,但是由于某种原因返回andrew。我怎样才能解决这个问题?你知道吗
字符串库有一个.count('name')函数。因此,您可以计算for循环中的每个元素,并对它们进行比较。你需要澄清这个问题,因为安德鲁和弗雷德出现过三次。你知道吗
“有道理……首先要有一个唯一名字的列表。然后用字典来储存它们。{name:[list\u names]然后是len(字符串)。编写一个函数,迭代字典并检索说话人最多的字典。”
不是直接回答家庭作业,而是一种可以用来解决这个问题和将来可能遇到的问题的技巧:在代码中添加
print
语句来理解正在发生的事情。例如,如果我们添加下面的两个print语句:它将打印以下输出:
如果第一次某个输出行没有意义,请查看是否可以找出原因。你知道吗
相关问题 更多 >
编程相关推荐