python只读取文件中的整数

Geo*_*rge 1 python

我无法想象从这个文件读取的方式,只有整数:

34
-1
2 48
  +0
++2
+1
 2.4
1000
-0
three
-1  
Run Code Online (Sandbox Code Playgroud)

该函数应返回:

[34, -1, 0, 1, -1]
Run Code Online (Sandbox Code Playgroud)

如果数字有效+-有效.但如果它有++或任何字母不是.

如果它有空格(例如2 48)无效.

如果> 999则无效.

我只被困在这里:

my_list = []
with open('test.txt') as f:
    lines = f.readlines()
    for line in lines:
        my_list.append(line.strip())
Run Code Online (Sandbox Code Playgroud)

我试图使它成为一个字符串并使用标点符号translate但我不确定它是否变得更复杂.

另外,我不确定使用正则表达式.我尝试了一个简单的正则表达式,但我没有使用它的经验.

Yev*_*ych 7

您可以使用将字符串转换为整数int().ValueError如果string不是整数,它将抛出.试试这个:

my_list = []
with open('test.txt') as f:
    for line in f:
        try:
            n = int(line)
            if n > 999 or line.strip() == '-0': continue #filtering numbers >999 and strings with '-0'
            my_list.append(n)
        except ValueError:
            pass

print(my_list)
Run Code Online (Sandbox Code Playgroud)

输出: [34, -1, 0, 1, -1]


Qic*_*hao 5

如果你想通过正则表达式这样做:

import re
exp = re.compile(r'^[\+,\-]?[0-9]{1,3}$')

my_list = []
with open('input.txt') as f:
    lines = f.readlines()
    for line in lines:
        if re.match(exp, line.strip()):
            my_list.append(int(line.strip()))
Run Code Online (Sandbox Code Playgroud)

让我们解释一下正则表达式.

^[\+,\-]?- ^装置的表达式必须与下一个限定符,这是两个字符的列表开始\+\-.我们需要在那里使用转义斜杠来实际放入特殊字符.最后一个?使前面的参数可选(因此字符串可以以+或 - 开头,或者什么都没有).

[0-9]{1,3}$- [0-9]指定作为数字的字符集.{1,3}指定它们应至少出现一次,或最多出现3次(因此满足您的<999约束.$符号匹配字符串的结尾,因此字符串必须以这组字符结束.

希望这一切都有帮助.