我正在尝试计算.txt文件行中第一个名称后面的名称数量,以使用以下代码确定使用python后名称最多的人:
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。我该如何解决这个问题?
答案 0 :(得分:0)
wordCount=0
mostWordsInLine = 0
follows = open("follows.txt", "r")
mostFollows = []
for word in follows:
f1=word.split()
wordCount += len(f1)
if len(f1) > mostWordsInLine:
mostWordsInLine = len(f1)
mostFollows = [f1[0]]
elif len(f1) == mostWordsInLine:
mostFollows.append(f1[0])
print ("Most social user: " + ''.join(mostFollows))
答案 1 :(得分:0)
不能直接回答家庭作业,但可以使用一种技术来解决您可能遇到的此问题和未来问题:在代码中添加print
语句以了解正在发生的事情。例如,如果我们在下面添加2个打印语句:
for word in follows:
lines += 1
f1=word.split()
wordCount=wordCount+len(f1)
print("f1 = {}, mostWordsInLine = {}".format(f1, mostWordsInLine))
if len(f1) > mostWordsInLine:
mostWordsInLine = len(f1)
mostWordsInLine = word[: word.find(' ')]
print(" after comparison: mostWordsInLine = {}".format(mostWordsInLine))
它将打印以下输出:
f1 = ['andrew', 'fred'], mostWordsInLine = 0
after comparison: mostWordsInLine = andrew
f1 = ['fred'], mostWordsInLine = andrew
after comparison: mostWordsInLine = andrew
f1 = ['judy', 'andrew', 'fred'], mostWordsInLine = andrew
after comparison: mostWordsInLine = andrew
f1 = ['george', 'judy', 'andrew'], mostWordsInLine = andrew
after comparison: mostWordsInLine = andrew
f1 = ['john', 'george'], mostWordsInLine = andrew
after comparison: mostWordsInLine = andrew
f1 = [], mostWordsInLine = andrew
after comparison: mostWordsInLine = andrew
Most social user: andrew
第一次输出线之一没有意义,看看你能否找出原因。
答案 2 :(得分:-1)
字符串库有一个.count('name')函数。因此,您可以计算for循环中的每个元素并将它们全部进行比较。你需要澄清问题,因为andrew和fred会发生三次。
“有道理....首先要有一个唯一名称列表[名称]。然后使用字典来存储它们。{name:[list_names] then len(string)。编写一个迭代字典并检索的函数发言人最多的词典。“