【问题标题】:Read lines starting with numbers读取以数字开头的行
【发布时间】:2015-02-15 18:57:39
【问题描述】:

如何在 python 中只读取以数字开头的文件中的行,即

Hello World <--ignore
Lovely day
blah43 
blah
1234 <--read
blah12 <--ignore
blah 
3124 <--read
Not matter how many words there are <--ignore
blah 
0832 8423984 234892304 8239048324 8023948<--read
blah132 <--ignore

【问题讨论】:

    标签: python list readfile file-handling


    【解决方案1】:
    import re
    with open("filename") as f:
        for line in f:
            if re.match(r"^\d+.*$",line):
                print line
    

    【讨论】:

    【解决方案2】:

    你可以使用isdigit()函数:

    for line in open('f.txt','r'):
       if line[0].isdigit():
           print line
    

    【讨论】:

    • 请注意,isdigit() 对数字的定义可能令人惊讶,它可能对手头的用例有效,也可能无效。它包括您期望的所有数字,还包括some unicode characters you might not
    • isdigit 用于测试字符串是否以数字开头?
    • @Haketo 当应用于第一个字符时,就像这里一样。
    • @Haketo isdigit() 如果字符串中的所有字符都是数字并且至少有一个字符,则返回true,否则返回false
    猜你喜欢
    • 2021-11-11
    • 1970-01-01
    • 2020-05-28
    • 1970-01-01
    • 1970-01-01
    • 2023-03-27
    • 2016-01-31
    • 2016-06-28
    • 1970-01-01
    相关资源
    最近更新 更多