简体   繁体   English

如何从文本文件中挑选出整数和字符串?

[英]How to sort out integers and strings from a textfile?

So I'm trying to create a program wich reads a text file and outputs the strings and integers in some sortations. 因此,我正在尝试创建一个程序,该程序可读取文本文件并以某种排序方式输出字符串和整数。

I'd like to print out at which row the strings were at and also create lists with all the integers in the text file. 我想打印出字符串在哪一行,并用文本文件中的所有整数创建列表。 (To further use the integers to find min, max, median etc) (进一步使用整数查找最小值,最大值,中位数等)

Ive tried and got stuck completely unfortunally. 我已经尝试过,不幸完全卡住了。

def readfile(file):
    try:
        f = open(file, 'r')
        fil = f.readlines()
        f.close()
        return fil
    except IOError:
        print('fil finns inte')
        return None

def rader(rowlist):
    k=rowlist
    l=[]
    try:
        for i in k:
            l.append(int(i.strip()))
            return l
    except:
        print("sds")

So this code is obviosuly not finished and also is currently run with a doctest. 因此,这段代码显然还没有完成,并且当前还与doctest一起运行。 Im stuck at the part where i want to sort the integers to a list and the strings to print out togeather with the row number. 我卡在我想将整数排序到列表和字符串以与行号一起打印出来的部分。

So obviosuly I'd like a loop which goes through a list of the document, when it hits an integer, append it to a list and when it hits an string, stop, just to the except case or something like that, and print the string out togeather with the number of the row (i). 因此,我很想让循环遍历文档列表,当它命中一个整数时,将其附加到一个列表中,当它命中一个字符串时,停止,直到例外情况或类似的情况,然后打印用行号(i)排列在一起。

How do i create this? 我该如何创建? I'm not looking for a very complicated program, but more a simple loop which I just cant see in my head how to code. 我不是在寻找一个非常复杂的程序,而是一个简单的循环,我只是在脑海中看不到如何编码。

Your's truely, a distressed student. 你是真的,一个心疼的学生。

Please see an example: 请看一个例​​子:

def get_integer_or_none(text):
    '''
    Returns integer from text or None if text is not an integer.
    '''
    try:
        return int(text)
    except ValueError:
        return None

for text in ('1', 'some text', '2 not an integer', '-1000'):
    integer_value = get_integer_or_none(text)
    if integer_value is not None:
        print('This text "{}" is an integer ({})'.format(text, integer_value))
    else:
        print('This text "{}" is not an integer'.format(text))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM