如何检查有多少行以数字开头

时间:2016-03-20 13:29:03

标签: python string for-loop split

假设字符串“text”代表多行,我如何计算以数字开头的行数?

def digit_leading_lines(text):
    n = 0
    newlist = text.split()
    for i in range (len(newlist)):
        for j in range (len(newlist[i])):
            if newlist[i][j].isdigit() == True:
                n += 1
    return n 

一旦我使用text ='AAA\n1st'对其进行测试,它会将正确的输出设为1。 但是当我输入text =“\t4G\nHz\n”时,导致第一行以制表符开头,输出应为0.但是,它仍然给我1作为输出。

当我测试“0\n0 3\n\n”时,它给出了错误的输出3.感谢您的帮助。

6 个答案:

答案 0 :(得分:4)

解决方案是:

def digit_leading_lines(text):
    lines = text.splitlines()
    count = 0
    for line in lines:
        if line and line[0].isdigit():
            count += 1
    return count

答案 1 :(得分:2)

为什么您的代码不起作用

那是因为你在每一行中的每个字符上循环。您的输出有意义,因为它只计算文件中的位数,而 开头的行。

让它发挥作用

您的问题有很多可能的解决方案,直接的解决方案是在线上迭代,并且只检查每一行的第一个字符:

with open('file') as f:
    lines = f.readlines()
    for line in lines:
        # check if the first character is a digit
        # and increment the count

终身提示:始终调试代码以更好地了解其流程

答案 2 :(得分:0)

您正在使用.split()取出所有空格。相反,请使用.splitlines()。此外,您可以使用生成器表达式执行此操作:

def digit_leading_lines(text):
    return sum(1 for line in text.splitlines() if line and line[0].isdigit())

答案 3 :(得分:0)

您可以使用'\ n'参数调用split方法,以便它仅基于换行符进行拆分。然后,您可以像下面的代码一样简化数值检查。

def digit_leading_lines(text):
    n = 0
    newlist = text.split('\n')
    for l in newlist:
        if len(l) and l[0].isdigit():
            n += 1
    return n

print digit_leading_lines("\t4G\nHz\n")

答案 4 :(得分:0)

使用正则表达式尝试此代码段:

data = """
The volcano is covered by a thick ice cap,
one of the largest in the tropics,
5 that has existed since at least the Pliocene and has
3 undergone several phases of expansion and reduction. As of
2016, the ice cap is in retreat; one estimate predicts that
it will disappear by
2045. The retreat of the Coropuna glaciers threatens the water
supply of tens of thousands of people,
and interaction between volcanic activity and glacial effects has
45 generated mudflows that could be a hazard to surrounding populations
if the mountain returns to volcanic activity.
"""

rx = re.compile(r"^\d", re.IGNORECASE | re.DOTALL | re.MULTILINE)

count = 0
for match in rx.finditer(data):
    count += 1

print(count)

输出:5

data包含您的多行文字。

答案 5 :(得分:0)

Python允许您完全按照自己的意愿行事:对所有行进行求和,其中第一个字母为数字。您可以在数值上下文中使用False或空字符串具有值1的事实并总结:

sum(
    (line and line[0]).isdigit() 
    for line in text.splitlines()
)

当行为空时,您需要(line and line[0])以避免IndexError,在这种情况下,返回第一个假值(空字符串),这不是数字,因此返回False。< / p>