[英]Python - Can't figure Out Why Regex Does and Doesn't Work In These Codes?
我是python的新手,我已經開始學習一些正則表達式。 我一直試圖在字符串中找到一些文本的匹配,並且碰到了一些我不理解的東西。 這是我的代碼:
import re
pattern1 = r'\b\w+\b,\s\b\w+\b'
pattern2 = r'\b\w+\b,\s\b\w+\b,'
# pattern1 produces expected result
with open('test_sentence.txt', 'r') as input_f:
for line in input_f:
word = re.search(pattern1, line)
print word.group()
# pattern 2, same as pattern1 but with additional ',' at the end
# does not work.
with open('test_sentence.txt', 'r') as input_f:
for line in input_f:
word = re.search(pattern2, line)
print word.group()
以下是test_sentence.txt的內容:
I need to buy are bacon, cheese and eggs.
I also need to buy milk, cheese, and bacon.
What's your favorite: milk, cheese or eggs.
What's my favorite: milk, bacon, or eggs.
我無法理解為什么pattern2
不起作用它拋出一個none-type object has no attribute group
在引用print word.group()
none-type object has no attribute group
錯誤。 我相信這意味着找不到匹配'pattern2'的正則表達式代碼。 為什么額外的,
最終導致這個問題? 為什么它不僅僅匹配milk, cheese,' and
牛奶,培根,?
您正在搜索每一行而不是整個文件。 這意味着有多行,其中pattern2將不匹配,並且將返回None
,這將導致錯誤。 將第二行移動到頂部,您將看到此行匹配,並且稍后在第二行發生錯誤。
使用前請務必檢查返回值:
word = re.search(pattern2, line)
if word:
print word.group()
else:
print "No match"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.