访问列表中的元组值(现在尝试了几个小时 :( )

Acessing a tuple value in a list (trying for hours now :( )

我是 Python 初学者,任务是沿着相同的重复行拆分文档,然后将这些部分保存在不同的文件中。 我拆分了行,然后尝试将其放入列表中的元组中。

f = open(PATENTS, 'r')
text =f.read()
n=0
counter=0
textblock=[]
stext= text.splitlines()

for lines in stext:
    if stext[n]!='<?xml version="1.0" encoding="UTF-8"?>':
        textblock.append((counter,stext[n]))

    else:
        counter+=1
    n+=1
print counter
print textblock[1][1]
f.close()

问题在于:

textblock[1][1]

它不起作用:(

我的计数器有效,if 语句也有效,有人可以给我提示吗?

我的文件是一个大文本文件,其中每个专利都以 if 语句中使用的行开头。现在我想把专利彼此分开。

所以我有一个在某种程度上看起来像这样的列表:

[(0,patenttext0),(1,patenttext1)...]

不太确定问题出在哪里,但我的印象是您想逐行打印行号。

您拥有的元组在索引 0 中存储行号,在索引 1 中存储文本。

在 python 3 的回复中:

>>> textBlock = []
>>> textBlock.append((1,"some text"))
>>> textBlock.append((2,"some more text"))
>>> for tuple in textBlock:
...     print(tuple[0], tuple[1])
...
1 some text
2 some more text
>>>

for python 2.7 将 print(...) 替换为 print tuple[0], tuple[1]

希望这就是您要找的。

textblock.append((counter,stext[n]))

您似乎在列表中存储一个元组。

请通过打印这样的列表来找出列表中的内容

print textblock

您的列表文本块必须看起来像这样

[(1,"line1),(2,"line2"),(3,"line3")]

列表是一维列表,您使用的索引类似于二维数组。

所以请尝试使用 textblock[1] 而不是 textblock[1][1] 不知道你想要达到什么目的。但是看你的评论似乎你需要打印列表中所有元组中的行,如果是这样的话,那么你需要遍历所有列表并打印该行。你应该使用这样的循环。

line = "" 
for i in range(len(textblock)) :
       line=line+textblock[i][1]
 print line

Python 索引从0开始,试试print textblock[0][0]

你也可以使用

for n in range(len(stext)):
        if stext[n]!='<?xml version="1.0" encoding="UTF-8"?>':
            textblock.append((counter,stext[n]))
        else:
            counter+=1

而不是

n=0
for lines in stext:
    if stext[n]!='<?xml version="1.0" encoding="UTF-8"?>':
        textblock.append((counter,stext[n]))

    else:
        counter+=1
    n+=1   

省去了n

的声明和增加

通过改变试试这个

if stext[n]!='<?xml version="1.0" encoding="UTF-8"?>':

if lines.strip() !='<?xml version="1.0" encoding="UTF-8"?>':

AND

textblock.append((counter,stext[n]))

textblock.append((counter,lines)) # or lines.strip()

那你要知道

  • 不需要

    text =f.read()
    stext= text.splitlines()
    

    刚刚

    stext = f.readlines() #will get list of lines