2013-01-16 126 views
1
def ints(filename): 
    a = [] 
    f = open(filename, "r") 
    lines = f.readlines() 
    f.close() 
    for line in lines: 
     numbers = line.split() 
     for number in numbers:    
      a.append(int(number)) 
    return a 

这是我的功能,到目前为止,我希望能够读取包含整数和字符,如“x”和“B”等文件,并只返回一个整数列表。目前该函数只能处理包含整数的文件。阅读和操作Python中的文件

如何修改此以排除字符或字母?

+1

你能举一个你期望的文件内容的例子吗? – thegrinner

回答

4

这是我对你的代码的编辑,执行如你期望它。

def ints(filename): 
     """A function that takes the filename of a file as an input arguement, computs and returns a list of 
     integers of all the numbers in the file.""" 
     a = [] 
     f = open(filename, "r") 
     lines = f.readlines() 
     f.close() 
     for line in lines: 
      for character in line: 
       try: 
        a.append(int(character)) 
       except ValueError: 
        pass 
     return a 
+1

奇怪的是,这已被接受,只适用于由空格包围的数字:'abc123cba'将忽略'123' – 2013-01-16 17:27:51

+0

@Mahi哦thanx的通知,但是,这是很容易解决的事情。 – NlightNFotis

+0

事实上,我已经修好了。 – NlightNFotis

2

regex在这儿可以帮忙:

一个简单的例子:

In [22]: import re 

In [23]: strs="121 some 34useless text 56" 

In [24]: map(int,re.findall("\d+",strs)) 
Out[24]: [121, 34, 56] 

# or this If you want the individual digits: 

In [40]: map(int,re.findall("\d",strs)) 
Out[40]: [1, 2, 1, 3, 4, 5, 6] 

为您的代码这应该工作:

for line in lines: 
    numbers = map(int,re.findall("\d+",line)) 
    a.extend(numbers) 
+1

+1好主意。虽然我坚信正则表达式在操作的这一点上很难,因为很明显他最近开始使用python。 – NlightNFotis

+0

你是指第二个例子中的'line'而不是'strs'? :) – 2013-01-16 17:16:13

+0

@Mahi很好的接收,忘了编辑。 –

0
for number in numbers: 
    try: 
     a.append(int(number)) 
    except ValueError: 
     pass 
0

的try/catch可能会有所帮助:

for thing in line.split(): 
    i_thing = None 
    try: 
     i_thing = int(thing) 
    except ValueError: 
     pass 

    s_thing = None 
    try: 
     s_thing = str(thing) 
    except: 
     raise Exception("OH NOES!") 

这实在是太丑陋,但我还没有找到一个更好的方式做你想要做的事。

1

我只是单纯的测试,如果字符是数字:

sample_string = "Test4. 2325This string3" 
a_list = [] 
for x in sample_string: 
    if x.isdigit(): 
     a_list.append(x) 
+0

1)它返回'['4','2','3','2','5','3']'而不是'[4,2325,3]'。 2)用'a.append(x)'我想你实际上是指'a_list.append(x)'? –

+0

@AshwiniChaudhary是的。我很sl。。 – Ci3

0

使用更现代的Python的成语:

def ints(filename): 
    with open(filename, "r") as f: 
     for line in f: 
      for number in line.split(): 
       try: 
        yield int(number) 
       except ValueError: 
        pass 


a = list(ints("testdata.txt")) 
print(a) 

基本上,尝试将转换为int,这将提高ValueError异常,如果该字符串不是一个十进制数。抓住它并忽略它并继续。

0

如何使用string.translate等将所有非数字替换为空格,然后利用split()和map()的功能。

当然,这是有点模糊的,我的默认响应是只使用re模块,因为整体而言,您可以使用正则表达式完成更多的工作,因此它们值得学习。

In [119]: import string 
In [120]: allchars = string.maketrans('', '') 
In [121]: delchars = allchars.translate(allchars, "") 
In [122]: emptychars = string.maketrans(delchars, ' ' * len(delchars)) 
In [123]: "Welcome home 1234 56 ol".translate(emptychars) 
Out[123]: '    1234 56 ' 
In [124]: "Welcome home 1234 56 ol".translate(emptychars).split() 
Out[124]: ['1234', '56'] 
In [125]: map(int, "Welcome home 1234 56 ol".translate(emptychars).split()) 
Out[125]: [1234, 56] 
0

这是未经测试的sudo代码,但应该是有效的。另外,我可以给出的最好建议是观看David Beazley的系统程序员生成器技巧和掌握Python 3 I/O会谈。他们对学习python非常有帮助。

这只是一个简单的生成器,用于获取文件的每一行,然后关闭文件。

def getLine(fileName): 
    file = open(fileName, "r") 

    for line in file.readLines(): 
     yield line 

    file.close() 


def getNumbers(line): 
// I'm lazy and stole this one from Keith 
    for number in line.split(): 
     try: 
      yield int(number) 
     except ValueError: 
      pass 

def generatorChain(fileName): 
    // I'm a little iffy on the syntax here, but shouldn't be to hard with a bit of googling 
    fileGen = getLine(fileName); 
    yield getNumber(fileGen.next()).next() 

def listCompressionMagic(): 
    return [x for x in generatorChain("foo.txt") ]