读取文件时如何删除行的第一部分?

2024-09-27 21:30:03 发布

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

我在一个名为“test.txt”的python文档中找到了这个数字列表:

1 2
2 3
3 2
4 5
5 2
6 3
7 7
8 2
9 11
10 13
11 2
12 3
13 5
14 17
15 19
16 2
17 23
18 7
19 29
20 3
21 31
22 2
23 37
24 41
25 43
26 47
27 5
28 53
29 59
30 2

我试图删除每行的第一个数字,并将第二个数字作为整数放入列表中,如下所示:

[2, 3, 2, 5, 2, 3, 7, 2, 11, 13, 2, 3, 5, 17, 19, 2, 23, 7, 29, 3, 31, 2, 37, 41, 43, 47, 5, 53, 59, 2]

我尝试过以下代码:

from inspect import currentframe, getframeinfo

frameinfo = getframeinfo(currentframe())

with open("test.py", "rt") as openfile:
   new_list = []
   for line in openfile:
       new_list.append(line.rstrip(str(frameinfo.lineno())))

print(new_list)

但它给了我一个错误:

Traceback (most recent call last):
  File "fileLocation", line 8, in <module>
    new_list.append(line.rstrip(str(frameinfo.lineno())))
TypeError: 'int' object is not callable

有人能解决这个问题吗


Tags: intest列表newline数字listappend
3条回答

Tim Biegeleisen的答案应该很有效。
另一种简单的方法是使用拆分行(在条带化之后),并获取第二个元素

with open("test.py", "rt") as openfile:
    new_list = []
    for line in openfile:
        try:
            new_list.append(line.strip().split(' ')[1])
        except IndexError:
            pass

print(new_list)

您可以在此处使用re.sub

with open("test.py", "rt") as openfile:
    new_list = []
    for line in openfile:
        new_list.append(re.sub(r'^\d+\s+', '', line))

模式^\d+\s+将匹配以行号开头的任何行的前导数字(以及后面的空格)

一个简单的解决方案是使用numpy:

import numpy as np
x = np.genfromtxt('test.py')
new_list = x[:,1]

相关问题 更多 >

    热门问题