Python,从文件中逐个读取行

2024-09-28 20:20:30 发布

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

我正在制作一个程序,它能区分有效和无效的社会保险号码。在

这个程序应该能够从我电脑上的文本文件中对数字进行排序。但是我只能一次输入所有的数字(我想)。我不会让程序逐一核对数字。在

这就是现在的样子

def fileinput():
    try:
        textfile = open("numberlist.txt","r")
        socialsecuritynumber = textfile.read()
        numberprogram(socialsecuritynumber)
    except IOError:
        print("there's no such file!\n")

有人知道我该怎么做吗? 文本文件只包含数字

  • 1993年6月11日5570
  • 930611-5570
  • 930611 5570
  • 93 05115570
  • 1993年05月11日55 70
  • 1993年05月11日5570

这是我文本文件中的数字


Tags: 程序排序def数字open号码区分文本文件
3条回答
with open("numberlist.txt") as f: # this auto closes the file after reading. It's good practice
    numbers = f.readlines() # numbers is a list of all the numbers(a list of lines in the file)

如果行中有不需要的空格(或者只是万一有):

^{pr2}$

如果你发现数字后面有逗号或其他东西,你可以这样做:

^{3}$

编辑:

或者,可以使用正则表达式,逗号和空格无关紧要:

import re

n = ['1993-06-11 5570',
     '930611-5570',
     '930611 5570',
     '93 05115570',
     '1993 05 11 55 70',
     '1993 05 11 5570']

regex = '([0-9]+(?:[- ]?[0-9]+)*)'
match_nums = [re.search(regex, num) for num in n]
results = [i.groups() for i in match_nums]
for i in results:
    print i

('1993-06-11 5570',)
('930611-5570',)
('930611 5570',)
('93 05115570',)
('1993 05 11 55 70',)
('1993 05 11 5570',)

有关正则表达式的信息,请参见here

  1. 总是用with语句读取文件。因此,如果在读取过程中出现问题,或者代码块中出现异常,文件将自动关闭。在
  2. 然后使用for循环逐行读取,如下所示

    with open("numberlist.txt","r") as textfile:
        for line in textfile:
            print line
    

按你的建议与fourtheye一起使用。您可以使用readLines()方法,并使用for-in循环逐个迭代这些行并检查其有效性。不保证你的大文件不会被破坏。在

相关问题 更多 >