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

2024-06-06 15:19:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图完成一个工作表,但又卡住了。我需要存储在一个列表中的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()

Tags: oftheinforiflinepeoplecomments
2条回答

问题不在前两个if语句上,而在第三个if语句上,因为第三个if语句的第一部分总是真的。然后它将只保存第二个if语句中创建者注释的第一个空行。@juanpa,if '>>>' in line and 'Mooneye Studios' not in line提到的改变可能会解决这个问题。你知道吗

代码中还有另一个问题,如果文件中的最后一个注释来自creator,它将不会保存到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.')

首先,对于第一个条件之后的条件,ifelif不同。 在第二种情况下,只经过一个分支,在第一种情况下,经过条件为真的所有分支。你知道吗

接下来,特别是如果你是一个初学者,你应该总是在纸上描述你想要达到的目标,用不同的方式说清楚描述算法,测试和分支。再想一想,算法是否能正确处理角落的情况,天气重新排序测试可以避免多次测试相同的条件:它将节省执行时间,并将简化未来的代码修改,因为将有较少的重复。只有在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
...

相关问题 更多 >