簡體   English   中英

如何檢查多少行以數字開頭

[英]How to check how many line start with digit

假設字符串“ 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 ”時,這導致第一行以tab開始,並且輸出應為0但是,它仍然給我1作為輸出。

而當我測試“ 0\\n0 3\\n\\n ”時,會給我錯誤的輸出3。謝謝您的幫助。

解決方法是:

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

為什么您的代碼不起作用

那是因為您要循環每一行中的每個字符。 您的輸出很有意義,因為它只計算文件中的位數,而不是數字開頭的行。

使它工作

對於您的問題,有許多可能的解決方案,直接的解決方案是在行上迭代,並且僅檢查每行上的第一個字符:

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

生活小貼士:始終調試代碼以更好地了解其流程

您正在使用.split()刪除所有空白。 而是使用.splitlines() 另外,您可以使用生成器表達式執行此操作:

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

您可以使用'\\ 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")

使用正則表達式嘗試以下代碼片段:

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包含多行文本的位置。

Python允許您精確地執行所需的操作:將所有行加和,其中第一個字母為數字。 您可以使用以下事實: False或空字符串在數字上下文中的值為1並求和:

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

當行為空時,您需要(line and line[0])避免IndexError ,在這種情況下,將返回第一個偽造的值(空字符串),該值不是數字,因此返回False

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM