簡體   English   中英

Python正則表達式NoneType錯誤

[英]Python regular expression NoneType error

我有一個名為“filename.txt”的文本文件

文件內容:

    This is just a text
    content to store
    in a file.

我已經制作了兩個python腳本來從文本文件中提取“to”

我的第一個劇本:

     #!/usr/bin/python
     import re
     f = open("filename.txt","r")
     for line in f:
              text = re.match(r"content (\S+) store",line)
              x = text.group(1)
              print x

我的第二個劇本:

    #!/usr/bin/python
    import re
    f = open("filename.txt","r")
    for line in f:
             text = re.match(r"content (\S+) store",line)
             if text:
                    x = text.group(1)
                    print x

第二個腳本提供正確的輸出

 bash-3.2$ ./script2.py
 to

但第一個腳本給了我一個錯誤

bash-3.2$ ./script1.py
Traceback (most recent call last):
File "./script1.py", line 6, in ?
x = text.group(1)
AttributeError: 'NoneType' object has no attribute 'group'

如何添加“if”條件給我正確的輸出,當我刪除它時我得到一個錯誤?

這是因為在您的第一個代碼中,您的正則表達式無法匹配任何內容,因此textNoneType 當您嘗試執行group它會拋出AttributeError: 'NoneType' object has no attribute 'group'錯誤

但是,對於正則表達式,您的代碼不會失敗,因為只有在實際匹配某些內容時才小心調用group

你的第二種方法更好,因為它不像第一種方法那樣是失敗證明。

這個錯誤對我來說是不言自明的:如果沒有找到匹配,則re.match返回None (參見doc )。

因此,當你的正則表達式不匹配(例如第一行)時,你試圖訪問NoneType對象的group屬性,它會拋出一個錯誤。

在另一種情況下,如果text不是None ,則只訪問該屬性(因為這是if text: check,以及其他內容)。

暫無
暫無

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

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