使用for循环从.txt创建列表

时间:2016-11-11 10:33:22

标签: python list for-loop

我正在尝试填写一张工作表,但又被卡住了。我需要将Mooneye Studios的所有评论存储在每次有来自项目创建者的新评论时更新的列表中。我试图在for循环中使用前两个条件。我得到月亮= [\ 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()

2 个答案:

答案 0 :(得分:0)

首先,对于第一个条件之后的条件,ifelif不同。 在第二种情况下,您只传递一个分支,在第一种情况下,您传递条件为真的所有分支。

接下来,特别是如果你是初学者,你应该总是在纸上描述你想要达到的目标,不同地说明了algorythm,测试和分支。并且想一想algorythm是否正确处理了极端情况,并且天气重新排序测试可以避免多次测试相同的条件:它将节省执行时间并且将简化将来修改代码,因为重复次数会减少。然后才用Python代码转换它。

最后,当你没有得到预期的结果并且不理解为什么时,只需在代码中添加跟踪以轻松地跟踪实际执行的行,或者使用Python的调试模式。

您当前的代码可能会变得(或多或少):

with open('lostEmberComments.txt', 'r') as comments:
    nbOfCom = 0
    people = []
    moon = []
    tmp = ''
    for line in comments:
        if line.startswith('>>>'):  # start of a new comment
            nbOfCom += 1            # count it
            if (len(tmp.strip()) != 0) and creator: # was previous a creator's one
                moon.append(tmp)    # store it
            tmp = ''
            if 'Mooneye Studios' in line:  # process current comment
                creator = True
            else:
                creator = False
                line = line.rstrip()       # not a creator's one
                if not line in people:     # add the name if is does not already exists
                    people.append(line)
        elif creator:
            tmp += line             # a continuing line of a creator's comment

# print the results
...

答案 1 :(得分:0)

问题不在前两个 if语句上,而是在第三个​​ if语句上,因为第三个if语句的第一部分('>>>')是总是如此。然后,它将仅通过 second if语句保存创建者注释的第一个空行。 @juanpa if '>>>' in line and 'Mooneye Studios' not in line提到的变化可能会解决问题。

您的代码还有另一个问题,即如果文件中的最后一条评论来自创作者,则不会将其保存到moon[]

以下是我建议的解决方案:

nbOfCom = 0
people = []
creator = False
moon = []
temp = ''

with open('lostEmberComments.txt') as comments:
    for line in comments:
        if line.startswith('>>> '): # start of new comment
            nbOfCom += 1
            if temp and creator: # previous comment is from creator
                moon.append(temp)
                temp = ''
            commenter = line.rstrip()[4:] # get the commenter's name
            creator = 'Mooneye Studios' == commenter
            if commenter not in people:
                people.append(commenter)
        elif creator:
            temp += line # save creator's comment

# don't miss the last comment in file if it is from creator
if temp and creator:
    moon.append(temp)

print(moon)
print('Discussion participants:', people)
print('There are', len(people), 'contributors to the discussion.')
print('There are', nbOfCom, 'commentaries on this project.')