我试图完成一个工作表,但又卡住了。我需要存储在一个列表中的Mooneye工作室的所有评论,每次有一个新的项目的创建者的评论更新。我试图用for循环中的前两个条件来实现这一点。我得到moon=[\n,\n,\n…]。你知道如何进行并使这项工作顺利进行吗? 文件看起来像http://imgur.com/bsSr06q。你知道吗
comments = open('lostEmberComments.txt', 'r')
nbOfCom = 0 #counting the commentaries
people = []# list of ppl who have commented
creator = False # did the creator write the comment?
moon = [] # lists of comments made by the creator
temp= ''
for line in comments:
# my attempt
if '>>> Mooneye Studios' in line:
creator = True
if creator and '>>>' not in line:
temp += line
if '>>>' and 'Mooneye Studios' not in line:
creator = False
if temp != '':
moon.append(temp)
temp = ''
# this section is for the first part of the excercise
if '>>>' in line:
nbOfCom += 1 # counting the commentaries
if not line.rstrip('\n') in people: # avoiding duplicates
people.append(line.rstrip('\n'))
b = len(people)
print(moon)
print('Discussion participants: ', people)
print('There are ', b, 'contributors to the discussion.')
print('There are ',nbOfCom,' commentaries on this project.')
comments.close()
问题不在前两个if语句上,而在第三个if语句上,因为第三个if语句的第一部分总是真的。然后它将只保存第二个if语句中创建者注释的第一个空行。@juanpa,
if '>>>' in line and 'Mooneye Studios' not in line
提到的改变可能会解决这个问题。你知道吗代码中还有另一个问题,如果文件中的最后一个注释来自creator,它将不会保存到
moon[]
。你知道吗下面是我建议的解决方案:
首先,对于第一个条件之后的条件,
if
与elif
不同。 在第二种情况下,只经过一个分支,在第一种情况下,经过条件为真的所有分支。你知道吗接下来,特别是如果你是一个初学者,你应该总是在纸上描述你想要达到的目标,用不同的方式说清楚描述算法,测试和分支。再想一想,算法是否能正确处理角落的情况,天气重新排序测试可以避免多次测试相同的条件:它将节省执行时间,并将简化未来的代码修改,因为将有较少的重复。只有在Python代码中转换它。你知道吗
最后,当您没有得到预期的结果并且不明白原因时,只需在代码中添加跟踪,就可以轻松地跟踪实际执行的行,或者使用Python的调试模式。你知道吗
您当前的代码可能会变成(或多或少):
相关问题 更多 >
编程相关推荐