如何从程序正在读取的行中删除行号?

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

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

我在一个名为测试.py“:”

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

我正在尝试删除每一行的第一个数字,而不必手动执行,因为列表有数千行长,但我尝试的这段代码不起作用:

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)

有人能解决这个问题吗?你知道吗


Tags: 代码frompy列表newline数字手动
3条回答

您可以在这里使用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]

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)

相关问题 更多 >

    热门问题