从文本fi向列表中添加多个元素

2024-10-03 15:24:12 发布

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

try:
    fileName = 'C:\pro.txt'
    textF = open(fileName, 'r')
    lines = textF.read()
except IOError:
    print("Not found")

paragraph = lines.split('\n\n')
paragraph[:] = (words for words in paragraph if words != '\t')

for w in paragraph:
    if w.isupper() == True:
        paragraphUpper = []
        paragraphUpper.extend([w])
        print(paragraphUpper[0])

嘿,大家好,所以我有一个小问题,添加几个元素到一个列表从文本文件。在这段代码中,我设法找到了所有大写的行,但是当我试图将它们作为新元素一个一个地添加到列表中时,却没有发生这种情况。它将整数作为数组的第一个元素添加。如何将行添加为新元素?你知道吗

我试过用分裂线分裂w。我试过只把段落分成一行而不是两行,但它仍然只在列表中添加一个元素。你知道吗

以下是文本文件的一个片段:

I

LAY OF THE LAND

There is a vast field of fascinating human interest, lying only just outside our doors, which as yet has been but little explored. It is the Field of Animal Intelligence.

Of all the kinds of interest attaching to the study of the world's wild animals, there are none that surpass the study of their minds, their morals, and the acts that they perform as the results of their mental processes.

In these pages, the term "animal" is not used in its most common and most restricted sense. It is intended to apply not only to quadrupeds, but also to all the vertebrate forms,--mammals, birds, reptiles, amphibians and fishes.

II

WILD ANIMAL TEMPERAMENT & INDIVIDUALITY

What I am trying to do here is, find the uppercase lines, and put them all in an array. Then, using the index method, I will find the first and last paragraphs of each section by comparing the indexes of these elements of this array I created.


Tags: andofthetoin元素列表is
3条回答

要获取大写行,请使用以下命令:

 try:
     fileName = 'C:\pro.txt'
     textF = open(fileName,'r')
     lines = textF.readlines()
  except IOError:
     print("Not found")
 UpperLines = []
 for line in lines:
     if line.isupper():
         UpperLines.append(line)
         print(line)

你可以很容易地用一个列表来理解这个问题。如果切换到readlines()paragraph[:] = ...行是无用的。这将满足您的需求:

try:
    fileName = 'C:\pro.txt'
    textF = open(fileName, 'r')
    paragraph = textF.readlines()
except IOError:
    print("Not found")

paragraphUpper = [w.strip() for w in paragraph if w.isupper()]
print paragraphUpper

如注释中所述,使用f.readlines();将文件拆分为行列表。你知道吗

在你的代码里还有很多奇怪的东西:

  • 对于列表理解,不需要执行paragraph[:];只需使用paragraph = ...重新分配变量。

  • 不要和True比较,只要做if w.isupper():

  • 每次通过循环时,您都将paragraphUpper重新定义为一个新的空列表;因此它将只包含一个元素。您需要在for语句之前创建一次。

  • 不要在列表中包装一个项目来执行paragraphUpper.extend([w]),只要执行paragraphUpper.append(w)

  • 使用一致的缩进;前几行有4个空格的缩进,最后的循环只有1个空格的缩进。Python标准是4。

相关问题 更多 >